2016-11-07 93 views
-4

我想從列表中使用尾部poninter鏈接列表的末尾添加數字,但我不明白爲什麼我的尾巴永遠不會改變。我想從鏈表中添加數字從列表中結束

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