2014-08-31 116 views
0

在下面的代碼中:插入函數不能插入多於2個節點。插入鏈接列表:Bug

#include <stdio.h> 
#include <stdlib.h> 

struct node 
{ 
int val; 
struct node * next; 
}; 

struct node * insertl(struct node * head,int value) 
{ 
    if(head==NULL) 
    { 
    struct node * temp= malloc(sizeof(struct node)); 
    temp->val = value; 
    temp->next=NULL; 
    head=temp; printf("%d",value); 
    return head; 
} 
if(head->next==NULL) 
{ 
    struct node * temp= malloc(sizeof(struct node)); 
    temp->val = value; 
    temp->next=NULL; 
    head->next = temp; printf("%d",value); 
    return head; 
} 
struct node *head1=head; 
while(!head1->next) 
{ 
    head1=head1->next; 
    printf("%d",head1->val); 
} 

struct node * temp= malloc(sizeof(struct node)); 
temp->val = value; 
temp->next=NULL; 
printf("%d",temp->val-90); 
head1->next = temp; 
return head; 
} 

    void print(struct node *head) 
{  printf("\n"); 
    struct node * temp = head; 
    while(temp!=NULL) 
    { 
    printf("%d\t",temp->val); 
    temp=temp->next; 
    } 

} 

int main() 
{ struct node * h =NULL; 
    h=insertl(h,1); 
    h=insertl(h,4); 
    h=insertl(h,1); 
    h=insertl(h,4); 
    print(h); 
} 

我在之間使用了printf語句來檢查代碼出錯的地方。 輸出顯示:1,4。爲什麼代碼不正確?

回答

2
struct node *head1=head; 
while(!head1->next) 
    ^

我想你試圖追加到列表的「結尾」,你的意思是while(head1->next)

+0

非常感謝您的快速回復。我感覺很糟糕,那很粗心 – user2047167 2014-08-31 15:18:57