【发布时间】:2013-11-10 02:04:37
【问题描述】:
首先,提前感谢所有回复此帖子的人。
其次,我浏览了所有其他帖子,但找不到任何对我有帮助的内容(抱歉,我是 C++ 新手)。
这是我的代码:
Node* Insert(Node *head,int data) //for linked lists
{
Node* current = head;
while(current -> next != NULL){
current = current -> next;
}
cout << head -> data;
Node *last = new Node();
last -> data = data;
last -> next = NULL;
current -> next = last;
return head;
}
似乎(通过行注释的反复试验)当前指针中下一个属性的访问似乎是问题所在,但我似乎无法弄清楚原因。 Node结构体有两个属性,*next(指向链表中的下一项)和data(节点的数据)。
有什么想法吗?
linux用户
编辑:问题已解决 - 非常感谢所有离开 cmets 的人!
遗憾的是,我无法使用 **pHead 取消引用解决方案,因为问题出在自动输入函数参数的网站上。然而,使用下面的 cmets,我制作了一个简单的程序,希望能为像我这样的其他初级 C++ 程序员详细说明这个问题:
Node* Insert(Node *head,int data)
{
if(head == NULL){
Node* last = new Node();
last -> data = data;
return last;
}
Node *current = head;
while(current -> next != NULL){
current = current -> next;
}
Node *last = new Node();
last -> data = data;
last -> next = NULL;
current -> next = last;
return head;
}
问候,
linux用户
【问题讨论】:
-
另外,当我尝试
head -> data时,我收到了一个段错误。 -
您确定
Nodes 总是将其下一个值初始化为NULL?也许向我们展示您如何初始化您操作的列表(即什么是头?)。此外,这看起来像append(),而不是insert()。 -
并非没有更多上下文。这叫什么?你确定调用者传入的是非空的
head? -
一开始,如果
head为NULL,那你就麻烦了。我建议函数的第一行应该是cout << head << endl; cout << head -> data << endl; -
感谢大家的快速响应——这是一个基本的 HackerRank 问题,它为您提供了一个链表,保证 *next 将始终指向另一个节点或 NULL。此外,它应该是 append(),但被命名为(默认情况下)插入 - 感谢您指出这一点。