c - 如何将节点插入到链表的尾部?
问题描述
我在弄清楚如何添加到链接列表的末尾时遇到了一些麻烦。出于某种原因,我的代码无法正常工作。而且我不确定它有什么问题。
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;
}
}
解决方案
我做了一些重写。这行得通吗?
CmdNode *insertCommand(CmdNode *head, CmdNode *new_CmdNode) {
if (head == NULL) return new_CmdNode;
CmdNode *p;
for (p = head; p->next != NULL; p = p->next);
p->next = new_CmdNode;
return head;
}
此外,跟踪尾部并将其添加到其中可能是值得的,因为这样每次您想将一个元素添加到列表中时,您都必须遍历所有元素才能到达末尾。
推荐阅读
- php - 如何在 Laravel 的主刀片文件 Switch 语句中调用子刀片文件?
- javascript - 我的发送按钮没有向我的聊天框发送数据?它不起作用
- google-assistant-sdk - 我的 api 不会运行示例代码并且状态无法注册设备
- postgresql - 如何交换具有唯一且非空约束的外键引用?
- kubernetes - k8s中cpu限制应该决定多大?
- python - 并非所有参数都在 SQL 语句中使用 - 其他资源在回答这个问题时不够清楚
- android - 在 Android Kotlin 中添加 admob 横幅/插页式广告时出现“无广告配置”
- python - 功能工具 - RollingSum
- python - Python Texttable - 每行的总宽度
- javascript - 管理多个用户的角色时如何避免速率限制?