How to create and use a linked list class in C++?

To create and use a C++ linked list class, you can follow these steps:

  1. Create a node class: A node class represents a node in a linked list, typically containing a data member and a pointer to the next node.
class Node {
public:
    int data;
    Node* next;
};
  1. Create a linked list class that includes methods for operations such as inserting, deleting, and printing nodes in the linked list.
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. Use the linked list class: In your main program, you can create a linked list object and utilize its methods.
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;
}

This is a simple example of a linked list class that you can modify and expand according to your needs.

bannerAds