所以我无法将节点插入链表的尾部。我理解这个概念,我相信我的代码是正确的,但我的程序总是崩溃。我在 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/