温馨提示×

c++链表类怎么创建使用

c++
小亿
92
2024-01-11 10:31:07
栏目: 编程语言

要创建和使用一个C++链表类,你可以按照以下步骤进行:

  1. 创建一个节点类:节点类表示链表中的一个节点,通常包含一个数据成员和一个指向下一个节点的指针。
class Node {
public:
    int data;
    Node* next;
};
  1. 创建链表类:链表类包含对链表的操作方法,如插入、删除和打印等。
class LinkedList {
private:
    Node* head;
public:
    LinkedList() {
        head = nullptr;  // 初始化链表为空
    }

    // 在链表末尾插入一个节点
    void insert(int value) {
        Node* newNode = new Node();
        newNode->data = value;
        newNode->next = nullptr;

        if (head == nullptr) {
            head = newNode;
        } else {
            Node* current = head;
            while (current->next != nullptr) {
                current = current->next;
            }
            current->next = newNode;
        }
    }

    // 删除指定值的节点
    void remove(int value) {
        if (head == nullptr) {
            return;
        }

        if (head->data == value) {
            Node* temp = head;
            head = head->next;
            delete temp;
            return;
        }

        Node* previous = head;
        Node* current = head->next;
        while (current != nullptr) {
            if (current->data == value) {
                previous->next = current->next;
                delete current;
                return;
            }
            previous = current;
            current = current->next;
        }
    }

    // 打印链表中的所有节点值
    void print() {
        Node* current = head;
        while (current != nullptr) {
            cout << current->data << " ";
            current = current->next;
        }
        cout << endl;
    }
};
  1. 使用链表类:在你的主程序中,你可以创建一个链表对象并使用它的方法。
int main() {
    LinkedList list;
    list.insert(1);
    list.insert(2);
    list.insert(3);
    list.print();  // 输出:1 2 3

    list.remove(2);
    list.print();  // 输出:1 3

    return 0;
}

这是一个简单的链表类的例子,你可以根据你的需求进行修改和扩展。

0