2016-11-07 3 views
-4

リンクリストの末尾にある尾のポインタを使用してリストから番号を追加しようとしていますが、尾は決して変化しません。リンクリストの末尾にあるリストから番号を追加しようとしています

struct node 
{ 
    int data; 
    struct node *next; 
}*head , *tail; 

typedef struct node NOD; 
//I addd the first node 
void addfirst(int num) 
{ 
    NOD *temp;//This is the new node 
    temp = (NOD*)malloc(sizeof(NOD)); 
    temp->data = num; 
    temp->next = NULL; 
    head = tail = temp; 
} 
//I add at the end of the list 
void add(int num) 
{ 
    NOD *temp; 
    temp = (NOD*)malloc(sizeof(NOD)); 
    temp->data = num; 
    temp->next = NULL; 
    tail->next = temp; 
    tail = temp; 
} 

int main() 
{ 
    int n , num, i; 
    freopen("intrare.txt" , "r" , stdin); 
    scanf("%d" , &n); 
    for(i = 0 ; i < n ; i++) 
    { 
     scanf("%d" , &num); 
     if(i==1) 
      addfirst(num); 
     else 
      add(num); 
    } 

    return 0; 
} 
+0

'if(i == 1)' - > 'if(i == 0)' – BLUEPIXY

+0

答えは – Radinator

答えて

0
temp->data = num; 
temp->next = NULL; 
head = tail = temp; 

変更このコード

temp->data = num; 
temp->next = head; 
head = temp; 

にあなたが先頭に追加している時に尾を変更する必要はありません。また、head = tail = temp;を実行すると、以前作成したリストが失われます。

+0

のように見えますが、addfirst関数は最初のノードを追加するためだけに使用されるので同じです。尻尾が常にNULLに等しいということは、最悪の場合でも悪いことです。 – Vladimir

関連する問題