首页 > 解决方案 > 如何将节点插入到链表的尾部?

问题描述

我在弄清楚如何添加到链接列表的末尾时遇到了一些麻烦。出于某种原因,我的代码无法正常工作。而且我不确定它有什么问题。

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;
    }
    
}

标签: clistfunctionlinked-list

解决方案


我做了一些重写。这行得通吗?

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;
}

此外,跟踪尾部并将其添加到其中可能是值得的,因为这样每次您想将一个元素添加到列表中时,您都必须遍历所有元素才能到达末尾。


推荐阅读