2011-09-13 41 views
1

我有以下單鏈表,即使我推3個元素,總是隻創建一個節點,我總是得到1的長度,請help.Thanks。Simple LInked list

#include <stdio.h> 

struct node 
{ 
    int data; 
    struct node *next; 

}; 

void push(struct node **head,int data) 
{ 
    struct node *temp = (struct node*)malloc(sizeof(struct node)); 
    temp->data=data; 
    if(*head == NULL) 
    { 
     *head=temp; 

    } 
    else 
    { 
    temp->next=*head; 
    *head=temp; 

    } 
} 

int length(struct node *head) 
{ 
    struct node *temp = head; 
    int count=0; 
    if(temp !=NULL) 
    { 
     count++; 
     printf("%d",temp->data); 
     temp=temp->next; 
    } 
    return count; 
} 
int main() 
{ 
    int a; 
    struct node *head=NULL; 
    push(&head,1); 
    push(&head,2); 
    push(&head,3); 

    a=length(head); 
    printf("%d",a); 
    return 0; 
} 

回答

5

在長度功能通過while更換if

2

在你length功能,改變這一行:

if(temp !=NULL) 

這樣:

while(temp != NULL) 
1

你有沒有注意到結構你的長度方法?您正在使用if語句,其中一個循環是適當的。您得到的答案是1,因爲您只執行一次count ++語句。

希望這會有所幫助。

1

錯誤來自push()函數。如果head不爲空,則需要遍歷列表到最後一個節點。如前所述while而不是if

0
# include <stdlib.h> 

void push(struct node **head,int data) 
{ 
struct node *temp; 

temp = malloc (sizeof *temp); 

temp->data = data; 
temp->next = *head; 
*head = temp; 
}