如何在构建链接列表时调整头、尾指针

How to adjust head, tail pointers when building a LinkedList

本文关键字:调整 指针 列表 构建 链接      更新时间:2023-10-16

我正在制作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.但我不明白为什么。当我这样做时,我专门更改了一个新的 ListNode 非空地址旁边的 headtail = new ListNode(data),但显然这并没有发生。我哪里出错了?

这是代码:http://cpp.sh/6ardx

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

当 list 为空并且您创建第一个节点时,插入第一个节点后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