2016-11-19 11 views
0

リンクリストの末尾にノードを挿入できません。私はそのコンセプトを理解しています。私のコードは正しいと思いますが、私のプログラムはクラッシュしています。私はリストの先頭に新しいノードを挿入する関数でメインで作成したリストを持っています。私はこれに問題はありませんが、関数はちょうどテールに挿入します。以下にコードを示します。リンクリストの末尾に新しいノードを挿入する

#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

find_last()機能であなたは

while(aux->next != NULL) 

はそう更新機能を使用して、最後のノードとして 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; 
} 

IS-書込み禁止すべきです。

+0

感謝を定義することができます。それは今働いている。 –

+1

あなたは正しくansをマークすることができます。 –

1

find_last関数は常にNULLを返します。 whileサイクルの条件はwhile (aux->next!= NULL)である必要があります。ループ

while(aux != NULL) { 

の条件はauxNULLに等しいときすなわち偽である場合にのみ内部ループが反復を停止するため

1

機能find_lastは常に

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

NULLを返します。

したがって、関数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); 
} 
関連する問題