在linkedList C++的开头插入

Inserting at the head of the linkedList C++

本文关键字:开头 插入 C++ linkedList      更新时间:2023-10-16

我正试图创建一个函数,让我在列表的开头插入节点。

这是我目前所掌握的,但我需要一些帮助和建议。你能放些光吗?既然快到感恩节了,我不想再被这个练习折磨了?

void List::insertAtHead(int addData) {
    nodePtr n = new node;
    n->next = NULL;
    n->data = addData;
    if(head != NULL){
        n->next = head;
        head = n;
    }
    else
    {
        head = n;
    }

尽管有node*,但它可以简化为:

void List::insertAtHead(int addData){
    node* n = new node;
    n->next = head;
    n->data = addData;
    head = n;
}

根据Zac Howland的建议:

struct node
{
    int data;
    node* next;
    node(int data,node* next)
        :data(data)
        ,next(next)
    {}
};
void List::insertAtHead(int addData){
    head = new node(addData,head);
}