【问题标题】:Adding nodes to end of a linked list in C在C中将节点添加到链表的末尾
【发布时间】:2013-12-22 14:41:42
【问题描述】:

我的代码是将节点添加到头部,但我希望将它们添加到尾部。我尝试将头指向下一个节点为空,但由于下一个节点为空而停止

if(head==NULL)
{
    head=node;
}
else
{
    node->next=head;
    node->prev=NULL;
    head->prev=node;
    head=node;
}
printf("The node is inserted to linked list succesfully. \n\n");
printMenu();

【问题讨论】:

  • 记得选择您认为最有帮助的答案并接受。整个堆栈的想法发挥作用非常重要。

标签: c linked-list


【解决方案1】:

您需要保留一个指向列表尾部的指针,然后添加一个元素可能如下所示:

node -> next = NULL;
tail -> next = node;
node -> prev = tail;
tail = node;

【讨论】:

  • 是的,我已经这样做了,但我没有将 tail 定义为与 head 不同的东西,所以用 tail 更改 head 的名称是行不通的
  • 这就是为什么你需要将tail 定义为不同于head 的东西:-)
  • 您的尾部包含指向列表中最后一个元素的指针,而不是第一个元素(最后一个表示下一个元素 = NULL)。有头你也可以很容易地得到你的尾巴:tail = head; while (tail->next != NULL) tail = tail->next;。请注意,最好将 tail 存储在一个变量中,而不是每次都通过遍历整个列表来获取它(与存储一个变量相比,这当然是昂贵的)。顺便说一句,在双向列表上操作时,同时存储 Head 和 Tail 指针是很常见的。
【解决方案2】:

你需要先到列表的末尾:

if(head==NULL)
{
    head=node;
}
else
{
  struct nodetype *p = head;
  while (p->next)
    p = p->next;
  p->next = node;
  node->prev = p;
}

【讨论】:

  • ...或者按照@Byakuya 所说的去做
  • nodetype 是你的结构的名称(你没有说它是什么)。我已经将它稍微修改为正确的 C - 仅使用类型的名称(而不是 struct nodetype)是 C++ 语法。
【解决方案3】:
// Create new node
struct nodeType *newNode = (struct nodeType *)malloc(sizeof(struct nodeType));

// Singly-linked list and new node is end of the list so the next pointer is NULL
newNode->next = NULL;

if(head==NULL){
    // If head is not assigned
    head = newNode;
}
else{
    // Assign the next pointer in the current node to the new node
    current->next = newNode;
}
// Update the current pointer to point to the newNode
current = newNode;

head 和 current 在哪里,

struct nodeType *head, *current;

如果当前指针不指向列表的末尾,您可以使用以下行遍历列表到末尾,然后开始追加到链表:

for(current = head; current->next != NULL; current = current->next);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 2014-02-02
    • 2013-11-13
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多