2017-04-11 119 views
0

所以我相當新的C和不得不使用鏈接列表的數據庫,我已經嘗試過,無法找到問題。當添加一個節點時,它會將其打印出來,但是當添加更多節點時,它僅在打印出最近添加的節點時循環,並且從不打印出最後一個節點(首先輸入的節點)。鏈接列表循環輸出在C

struct person 
{ 
    char sex; 
    int age; 
    struct person *prev, *next; 
}; 
struct person* first = NULL; 



static void add_person(void) 
{ 

struct person* temp = (struct person*)malloc(sizeof(struct person)); 
    if (temp == NULL) 
     printf("Unable to allocate memory"); 
{ 
printf("Enter the gender: "); 
scanf("%c", person->sex); 

printf("Enter the age: "); 
scanf("%d", person->age); 

if(first==NULL){ 
    temp->prev=NULL; 
    temp->next=NULL; 
    first=temp; 
} 
else{ 
    temp->prev=NULL; 
    temp->next=first; 
    first->prev=temp; 
    first=temp; 
} 
free(temp); 
} 


static void print(void) 
{ 
    struct person* present = first; 
    while(present != NULL){ 
    printf("%c", present->sex); 
    printf("%i", present->age); 
    present=present->next; 
    } 
+1

凡'start'變量聲明? – oklas

+1

也許'開始'應該是'第一'?爲什麼在返回之前釋放'temp'? –

+0

對不起,開始是第一,現在改變它。我應該不是在那個地方解放臨時工嗎? – birdleaf

回答

0

你應該把temp代替person

printf("Enter the gender: "); 
scanf(" %c", &temp->sex); 

printf("Enter the age: "); 
scanf("%d", &temp->age);