c - 在链表的尾部插入一个新节点

标签 c

所以我无法将节点插入链表的尾部。我理解这个概念,我相信我的代码是正确的,但我的程序总是崩溃。我在 main 中创建了我的列表,其中包含一个将新节点插入到列表头部的函数。我对此没有问题,但只是插入到尾部的功能。这是下面的代码。

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
    int number;
    struct node * next;
} Node;

typedef Node * Nodeptr;

void insertnode_tail(Nodeptr head);
Nodeptr find_last(Nodeptr head);

void insertnode_tail(Nodeptr head) // function to insert node at the tail.
{
    Nodeptr here = find_last(head);
    Nodeptr newentry = NULL;
    int n = 0;

    printf("Enter the value to be assigned to the new entry? \n");
    scanf("%d", &n);

    if((newentry = malloc(sizeof(Node))) == NULL) {
    printf("No Memory\n");
    exit(0);
    }

    newentry -> number = n;
    newentry -> next = NULL;
    here -> next = newentry;
    traverse1(head);
}


Nodeptr find_last(Nodeptr head) // Function to return the last node of list
{
    Nodeptr aux = head;
    int n = 0;
    while(aux != NULL) {
    aux = aux->next; // moves the aux pointer along the list
    n++;
 }

 return aux;
}

最佳答案

您的 find_last 函数总是返回 NULL。 while循环中的条件应该是while (aux->next!= NULL)

关于c - 在链表的尾部插入一个新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40695915/

相关文章:

c - 按升序重新排列数组中的数字并在 C 中打印它们

c - 如何对 UDP 协议(protocol)进行拥塞控制?

c - 不兼容的返回类型

c - 为什么我的小口齿不清的人不会引用?

c - 你怎么能 "avoid"SIGSEGV?

c++ - C/C++ 动态链接如何在不同平台上工作?

c++ - 按位非 (~) 的奇怪行为

c - 对动态分配的数组进行二分查找

c - 查找段落中单个字数的程序

c - 该函数的时间复杂度