所以我無法將節點插入鏈表的尾部。我理解這個概念,並且我相信我的代碼是正確的,但是我的程序不斷崩潰。我在main中創建了一個列表,其中添加了一個將新節點插入列表頭部的函數。我對此沒有任何問題,只是插入到尾部的函數。這是下面的代碼。在find_last()
功能在鏈表尾部插入一個新節點
#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;
}
感謝您的幫助。現在正在工作。 –
然後您可以標記ans正確。 –