C++用类实现链表
作者:野牛程序员:2023-07-05 07:53:47 C++阅读 2725
      当用C++实现链表时,可以使用类来表示链表的节点和链表本身。以下是一个简单的示例:
#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 insert(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 display() {
        Node* current = head;
        while (current != nullptr) {
            std::cout << current->data << " ";
            current = current->next;
        }
        std::cout << std::endl;
    }
};
int main() {
    LinkedList list;
    list.insert(10);
    list.insert(20);
    list.insert(30);
    list.display();
    return 0;
}在这个例子中,我们定义了两个类:Node和LinkedList。Node类表示链表中的节点,具有一个整数数据成员和一个指向下一个节点的指针成员。LinkedList类表示链表本身,具有一个指向链表头部的指针成员。
在LinkedList类中,我们实现了两个方法:insert和display。insert方法用于在链表末尾插入新节点,display方法用于打印链表的所有节点值。
在main函数中,我们创建了一个LinkedList对象并插入了三个节点。然后调用display方法来显示链表中的所有节点值。
注意:这只是一个简单的链表实现示例,没有包含错误处理和其他高级功能。在实际的应用中,可能需要更多的方法来操作链表,比如删除节点、查找节点等。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
        
- 上一篇:c++结构体链表
 - 下一篇:Python判断链表是否为回文链表
 
