构建LinkedList时如何调整头尾指针

How to adjust head, tail pointers when building a LinkedList

我正在做一个 LinkedList 的简单实现。我的试炼:

#include<bits/stdc++.h>

using namespace std;

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

int main()
{
    ListNode* head = NULL;
    ListNode* tail;
    int data;
    cout<<"Enter data. Enter -1 to terminate insertion"<<endl;
    while(1)
    {
        cin>>data;
        if(data != -1)
        {
            if(head == NULL)
            {
                head = new ListNode(data); // Returns the address of a new ListNode and stores it in head
                tail = head->next; // tail now points to head's next
            }
            else
            {
                tail = new ListNode(data); // address of a new ListNode is in tail
                tail = tail->next; // Tail now points to the new ListNode's next
            }
        }
        else
            break;
    }
    tail = NULL; // Tail ends with a NULL
    while(head)
    {
        cout<<head->val<<" ";
        head = head->next;
    }
}

当我输入 1、2、3 时:我希望链表形成为 1->2->3->NULL

但是,链表总是只有第一个元素1->NULL

我在调试器上 运行 实际上,head->next 总是 NULL。但我不明白为什么。当我执行 tail = new ListNode(data) 时,我专门将 head 更改为新的 ListNode 非空地址,但显然那没有发生。我哪里错了?

代码如下:http://cpp.sh/6ardx

问题: tail 始终为 NULL。 当 tail 为 NULL 时,您希望如何在 tail 和附加节点之间建立连接?

当列表为空并且您创建第一个节点时,在插入第一个节点后 headtail 应该指向同一个节点。改变

        if(head == NULL)
        {
            head = new ListNode(data); // Returns the address of a new ListNode and stores it in head
            tail = head->next; // tail now points to head's next
        }

        if(head == NULL)
        {
            tail = head = new ListNode(data); // Returns the address of a new ListNode and stores it in head
        }

第二个问题,当你添加到列表的末尾时,你应该更新tail->next指向插入的节点,所以更改

        tail = new ListNode(data); // address of a new ListNode is in tail
        tail = tail->next; // Tail now points to the new ListNode's next

        tail->next  = new ListNode(data); // address of a new ListNode is in tail
        tail = tail->next; // Tail now points to the new ListNode's next