简体   繁体   English

插入链表的末尾

[英]insert at end of linked list

I am writing a simple function to insert at the end of a linked list on C++, but finally it only shows the first data. 我正在编写一个简单的函数,将其插入C ++链表的末尾,但最终它仅显示第一个数据。 I can't figure what's wrong. 我不知道怎么了。 This is the function: 这是功能:

node* Insert(node* head, int data)
{
    if (head == NULL) {
        head = new node();

        head->data = data;
        head->link = NULL;

        return head;
    }
    else {
        node* temp = head;
        while (temp != NULL) {
            temp = temp->link;
        }

        node* temp2 = new node();

        temp2->data = data;
        temp2->link = NULL;
        (temp->link) = temp2;

        return head;
    }
}

Change the condition in while construct from: 从以下位置更改while构造中的条件:

while (temp!=NULL) {
    temp=temp->link;
}

To

while (temp->link!=NULL) {
    temp=temp->link;
}

In statement, temp->link = temp2 , temp is a null pointer. 在语句temp->link = temp2 ,temp是空指针。 You were dereferencing a NULL pointer. 您正在取消引用NULL指针。

To append a node at the back, temp pointer should point to the last node of the linked list. 要在后面附加一个节点, temp指针应指向链表的最后一个节点。 So, in the while loop, you need to just stop linked list traversal when you have reached the last node, ie, the node whose link member points to nothing ( has NULL ). 因此,在while循环中,您仅需在到达最后一个节点(即,其link成员指向无内容( has NULL )的节点)时停止遍历链表。 while (temp->link!=NULL) will stop at the last node as last node will have link member pointing to NULL . while (temp->link!=NULL)将在最后一个节点处停止,因为最后一个节点的link成员将指向NULL

You can simplify your logic by doing this: 您可以这样做来简化逻辑:

void Insert(node **pnode, int data)
{
    while (*pnode) {
        pnode = &(*pnode)->link;
    }
    *pnode = new node(data, NULL);
}

assuming you have a node constructor that initializes data and link from arguments. 假设您有一个node构造函数来初始化data并从参数link

Instead of calling it as 而不是称它为

head = Insert(head, 42);

you'd now do 你现在要做

Insert(&head, 42);
node* Insert(node* head, int data)
{
    if (head == NULL) {
        head = new node();
    }
    else {
        while (head->link != NULL) {
            head = head->link;
        }
        head = head->link = new node();
    }
    head->data = data;
    head->link = NULL;
    return head;
}

将while(temp!= NULL)更改为while(temp-> link!= NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM