如何在构建链接列表时调整头、尾指针
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
.但我不明白为什么。当我这样做时,我专门更改了一个新的 ListNode 非空地址旁边的 headtail = new ListNode(data)
,但显然这并没有发生。我哪里出错了?
这是代码:http://cpp.sh/6ardx
问题:tail
始终为 NULL。 当tail
为 NULL 时,您希望如何在和附加到列表中的节点之间建立连接tail
?
当 list 为空并且您创建第一个节点时,插入第一个节点后head
和tail
应指向同一节点。改变
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
相关文章:
- 调整大小后指向元素值的指针unordered_map有效?
- 如何在构建链接列表时调整头、尾指针
- 指向地址的指针似乎调整在范围之外
- 调整指针大小
- 调整双指针数组C++大小
- 如何判断 std::vector 是否调整了自身大小,以及如何解释指向向量内值的指针不再有效
- 调整窗口内存映射文件的大小,而不会使指针失效
- 如何使用3D char数组调整双指针2D char阵列的大小
- 在 void getData() 中,如何访问由 void* 指针重新调整的内存位置
- 如何调整属于类的唯一指针的字符数组的大小.它必须在程序的整个生命周期中保持活力
- 指针调整没有多重继承
- 指针调整大小的矢量
- 我需要调整指针数组的大小
- 调整指针数组 C++ 的大小
- C++在没有STL的情况下调整指针数组的大小(向量..)
- 调整指针segfault的向量大小
- 是否可以调整输入参数以采用指针而不是引用
- 带有指针的可调整大小数组
- 我是否应该期望单个继承中的向上转换和向下转换不会调整指针?
- 是否可以在不使指针无效的情况下调整/重新分配大块内存