阅读量:0
要使用类实现链表,首先需要定义一个节点类来表示链表的节点,然后再定义一个链表类来操作这些节点。
以下是一个使用类实现链表的示例:
#include <iostream> // 链表节点类 class Node { public: int data; Node* next; Node(int value) { data = value; next = nullptr; } }; // 链表类 class LinkedList { private: Node* head; // 链表头指针 public: LinkedList() { head = nullptr; } // 在链表尾部插入一个节点 void append(int value) { Node* newNode = new Node(value); if (head == nullptr) { head = newNode; } else { Node* current = head; while (current->next != nullptr) { current = current->next; } current->next = newNode; } } // 在链表指定位置插入一个节点 void insert(int value, int index) { if (index < 0) { std::cout << "Invalid index!" << std::endl; return; } Node* newNode = new Node(value); if (index == 0) { newNode->next = head; head = newNode; } else { Node* current = head; for (int i = 0; i < index - 1; i++) { if (current == nullptr) { std::cout << "Invalid index!" << std::endl; return; } current = current->next; } newNode->next = current->next; current->next = newNode; } } // 删除链表指定位置的节点 void remove(int index) { if (index < 0) { std::cout << "Invalid index!" << std::endl; return; } if (index == 0) { Node* temp = head; head = head->next; delete temp; } else { Node* current = head; for (int i = 0; i < index - 1; i++) { if (current == nullptr || current->next == nullptr) { std::cout << "Invalid index!" << std::endl; return; } current = current->next; } Node* temp = current->next; current->next = temp->next; delete temp; } } // 打印链表中的所有节点值 void print() { Node* current = head; while (current != nullptr) { std::cout << current->data << " "; current = current->next; } std::cout << std::endl; } }; int main() { LinkedList myList; myList.append(1); myList.append(2); myList.append(3); myList.insert(4, 1); myList.print(); // 输出:1 4 2 3 myList.remove(2); myList.print(); // 输出:1 4 3 return 0; }
在上述示例中,我们首先定义了一个节点类Node
,包含一个整型数据成员data
和一个指向下一个节点的指针next
。
然后,我们定义了一个链表类LinkedList
,包含一个指向链表头部的指针head
。链表类中实现了几种基本的链表操作,如在链表尾部插入节点、在指定位置插入节点、删除指定位置的节点以及打印链表中的所有节点。
在main
函数中,我们创建了一个链表对象myList
,并进行了一些插入、删除和打印操作,最后销毁链表对象。
运行上述示例代码,将输出如下结果:
1 4 2 3 1 4 3
这表明使用类实现的链表能够正常工作。