【发布时间】:2021-05-08 19:05:16
【问题描述】:
为什么我的输出在打印时没有显示包含14 的节点?
我想我在实现链表时遗漏了一些关键原则:
#include<iostream>
using namespace std;
struct ListNode
{
int value;
ListNode *next;
ListNode(int d,ListNode* p=NULL) //constructor
{
value=d;
next=p;
}
};
int main()
{
ListNode* header=NULL;
header=new ListNode(5);
ListNode* ptr=header; //pointer to find the correct position
ListNode* sptr=new ListNode(13);
header->next=sptr;
ListNode* tptr=new ListNode(19);
sptr->next=tptr;
ListNode* t=new ListNode(14);
while((ptr->value) < (t->value))
{
ptr=ptr->next;
}
ListNode* g=ptr;
ptr=t;
t->next=g;
while(header!=NULL)
{
cout<<header->value<<" ";
header=header->next;
}
return 0;
}
【问题讨论】:
-
从您的代码中不清楚您想要实现什么。您已经很好地实现了 ListNode 项,尽管您可能会将其设为模板,因此您不必将整数用作值。无论如何,“t”变量永远不会添加到您的原始列表中,因此您永远无法打印它。将 cmets 添加到代码中以明确您的意图。通常这也有助于自己找出问题所在。另见橡皮鸭调试:en.wikipedia.org/wiki/Rubber_duck_debugging
-
您将
ptr指向ListNode(14),但您没有将ListNode(13)->next指向ListNode(14)。您需要现有节点之一的 next 指针指向您的新节点。 -
@Welbog 为什么有必要?不是 ptr==sptr->next 即已经将节点 13 的地址指向 14 节点
标签: c++ data-structures linked-list insert singly-linked-list