2016-11-19 93 views
0

所以我無法將節點插入鏈表的尾部。我理解這個概念,並且我相信我的代碼是正確的,但是我的程序不斷崩潰。我在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; 
} 

回答

1

你應該爲寫

while(aux->next != NULL) 

所以更新的功能是 -

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

return aux; 
} 

你的程序崩潰,因爲你的最後一個節點返回NULL值。

+0

感謝您的幫助。現在正在工作。 –

+1

然後您可以標記ans正確。 –

1

您的find_last函數總是返回NULL。 while循環中的條件應爲while (aux->next!= NULL)

1

功能find_last,因爲它裏面的循環停止迭代,只有當環

while(aux != NULL) { 

的條件爲假也就是當aux等於NULL總是返回NULL

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; 
} 

因此,在函數insertnode_tail的這個聲明中,試圖解引用NULL指針。

here -> next = newentry; 

因此該函數具有未定義的行爲。

這些功能一般都是無效的。問題是如果一個節點被追加到一個空列表中,那麼頭部必須被更新。這意味着頭部必須通過參考傳遞給功能。

的功能可以被定義如下方式

Nodeptr * find_last(Nodeptr *head) // Function to return the last node of list 
{ 
    while(*head) head = &(*head)->next; 

    return head; 
} 

void insertnode_tail(Nodeptr *head) // function to insert node at the tail. 
{ 
    Nodeptr *here = find_last(head); 

    int n = 0; 

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

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

    (*here)->number = n; 
    (*here)-> next = NULL; 

    traverse1(*head); 
}