2016-07-27 41 views
1

即時嘗試添加節點在鏈接列表的開始,但在我的代碼中,它只顯示最後一個元素,我只輸入最後一個元素。問題的原因是什麼顯示功能鏈接列表代碼不工作

#include <stdio.h> 
//node structure 
struct node 
{ 
    int data; 
    struct node *next; 

}; 

//結構

//datatype declaration 
typedef struct node node ; 
// head pointer which will indicate starting point of link list 
node *head; 

//create fuction that will insert values into note and its next pointer field 
void create(int num); 
//display function will display the link list 
void display(); 

main() 
{ 

     int num,i,n; 

     printf("enter the nno of node to create : "); 
     scanf("%d",&n); 

     for(i=0;i<n;++i) 
     { 
      printf("enter data for node %d= ",i+1); 
      scanf("%d",&num); 
      create(num); 



     } 
     display(); 

//顯示呼叫

} 
void create(int num) 
{ 
     head=NULL; 
     node *temp; 
     temp=(node*)malloc(sizeof(node)); 
     temp->data=num; 
     temp->next=head; 
     head=temp; 




return; 
} 

//函數創建()端

void display() 
{ 
    node *temp1; 
    temp1=head; 

    while(temp1!=NULL) 
    { 
     printf("data : %d-> ",temp1->data); 
     temp1=temp1->next; 


    } 

return; 
} 

//溫控功能顯示()端

回答

0

你的主要問題是:

head=NULL; 

因此您的線路

temp->next=head; 

總是將下一個被NULL。因此,你所有的名單是長度爲1的 。

我建議任一聲明headstatic(和 因此從一開始就歸零),或在intializing mainhead

0

你的顯示功能似乎罰款,你創建函數應該是這個樣子:

void create(int num) 
{ 
node* temp = new node(); 

     if(head ==NULL) 

     { temp->data = num; 
      head = temp; 
      head->next = NULL; 
     } 
     else if(head->next == NULL) 
     { 
     temp->data = num; 
     head->next = temp; 
     } 
     else 
     { 
     node* temp2 = head; 
     while(temp2->next !=NULL) 
     { temp2 = temp2->next; 
     } 
     temp->data = num; 
     temp2->next = temp; 
     } 



return; 
} 

此創建功能上面會放置節點取決於如果該列表是空的,有一個節點或多個節點將插入Last位置。您現在可以將其放在頭部前面或鏈接列表項中(InsertBeforeFirst)。當然,如果你有節點* head up top應該初始化爲NULL;