C++链表实现及源码示例

habitual_37358 8 0 cpp 2023-10-02 10:10:34

C++链表实现是一种常用的数据结构,以下是list.cpp源码示例,供大家参考学习:

#include 
using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class List {
public:
    ListNode* head;

    // 构造函数
    List() {
        head = NULL;
    }

    // 在链表末尾插入一个节点
    void insert(int val) {
        ListNode* newNode = new ListNode(val);
        if (head == NULL) {
            head = newNode;
            return;
        }
        ListNode* cur = head;
        while (cur->;next != NULL) {
            cur = cur->;next;
        }
        cur->;next = newNode;
    }
};

int main() {
    List myList;
    myList.insert(1);
    myList.insert(2);
    myList.insert(3);
    return 0;
}

用户评论
请输入评论内容
评分:
暂无评论