如何解决如何将节点插入链表的尾部?
我在弄清楚如何添加到链接列表的末尾时遇到了一些麻烦。出于某种原因,我的代码无法正常工作。而且我不确定它有什么问题。
CmdNode *insertCommand(CmdNode *head,CmdNode *new_CmdNode) {
/**
* This function inserts the node new_CmdNode *at the tail* of the linked
* list. (You are adding a command at the end).
*
* If head == NULL,then the linked list is still empty.
*
* It returns a pointer to the head of the linked list with the new node
* added into it.
*
* Todo: Implement this function
*/
// check if head == NULL // list is empty >> return null and exit function
//CmdNode *p = NULL;
//p = head;
CmdNode *p = NULL;
p = head;
// if head is not empty
if(head != NULL)
{
//traverse the list
while(p->next != NULL)
{
// update p to the next node
p = p->next;
}
// at the end of its iteration p will point to null > update to new_Cmdnode
p->next = new_CmdNode;
// return the head of list
}
else
{
// if list is empty the cmdnode is head
head = new_CmdNode;
return head;
}
}
解决方法
问题在于这个语句
return head;
不在 if-else 语句之外。将其移到 if-else 语句之后。
if(head != NULL)
{
//...
}
else
{
//...
}
return head;
注意最初指向头节点的指针应设置为NULL。如果它是一个全局变量,那么它已经被编译器设置为 NULL。指针 new_CmdNode 指向的节点的 next 数据成员也应该已经设置为 NULL。
函数看起来像
CmdNode * insertCommand( CmdNode *head,CmdNode *new_CmdNode )
{
if ( head == NULL )
{
head = new_CmdNode;
}
else
{
CmdNode *p = head;
while ( p->next ) p = p->next;
p->next = new_CmdNode;
}
return head;
}
还请记住,如果您要向单向链表的尾部添加新节点,那么定义双边单向链表会更有效。那就是除了指向头节点的指针之外还要保留一个指向尾节点的指针。
,我做了一些重写。这行得通吗?
False
而且,跟踪尾部并将其添加到尾部可能是值得的,因为这样每次您想向列表中添加一个元素时,您都必须遍历所有元素才能到达结尾.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。