【发布时间】:2021-06-03 02:26:59
【问题描述】:
我在弄清楚如何添加到链接列表的末尾时遇到了一些麻烦。出于某种原因,我的代码无法正常工作。而且我不确定它有什么问题。
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;
}
}
【问题讨论】:
-
当您可以初始化为 head 时,为什么将 p 毫无意义地初始化为 NULL?
-
您应该可以将
// return the head of list替换为return head;。或者,由于if的两个分支最后都有return head;,所以将return head;语句移到函数的末尾。 -
另外,该函数的调用者需要将返回值赋给链表头指针,例如:
mylisthead = insertCommand(mylisthead, newnode);。 -
另外,需要将新节点的
next指针设置为NULL。如果调用者不这样做,则需要在insertCommand函数中进行:new_CmdNode->next = NULL;。 -
请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?
标签: c list function linked-list