繁体   English   中英

在链表的末尾插入节点

[英]Inserting a node at the end of a linked list

#include <stdio.h>
#include <conio.h>

struct node
{
    int data;
    struct node* next;
};

int main()
{
    struct node* head = NULL;
    struct node* second = NULL;
    struct node* third = NULL;

    head = (struct node*)malloc(sizeof(struct node));
    second = (struct node*)malloc(sizeof(struct node));
    third = (struct node*)malloc(sizeof(struct node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    struct node* new1;
    struct node* temp1;

    temp1 = head;

    while(temp1->next != NULL)
    {
        temp1 = temp1->next;
    }

    new1 = (struct node*)malloc(sizeof(struct node));

    temp1->next = new1;
    new1->data = 5;
    new1->next = NULL;

    while(temp1 != NULL)
    {
        printf("%d ",temp1->data);
        temp1 = temp1->next;
    }

    return 0;
}

这是在链表末尾插入节点的程序。 预期输出= 1 2 3 5,5这里是新节点的值。 但目前的输出是= 3 5.我不知道我错在哪里。 任何答案将不胜感激。

while(temp1->next != NULL)
 {
    temp1 = temp1->next;
 }

在此循环之后, temp1位于列表的末尾,并且您将在列表的末尾添加节点。

现在你试图从temp1打印显然你将只获得2个节点新节点和前面的节点。 如果你想head打印整个列表。 在添加新节点之后打印之前。 将temp1指向头部。

temp1 = head;
while(temp1 != NULL)
{
    printf("%d ",temp1->data);
    temp1 = temp1->next;
}

使用像你这样的东西时要记住的一件事就是到达列表的末尾:如果你只是说third->next = first ,那么它将永远持续下去。 这是值得注意的,也是您可能想要玩的东西。 也许可以考虑在某处添加一个list_size整数,以便不会发生无限循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM