2016-11-07 95 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