2011-09-13 22 views
1

私は次の単一リンクリストを持っています.3つの要素を押しても常に長さが1になります。常に1つのノードしか作成されません。助けてください。単純なLInkedリスト

#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

この行を変更、あなたのlength機能で長さ機能

2

whileによってifを置き換えます。これに

if(temp !=NULL) 

while(temp != NULL) 
1

を、あなたは構造に気づきましたあなたの長さの方法の?ループが適切なif文を使用しています。 count ++ステートメントを1回だけ実行しているので、答えは1です。

これが役に立ちます。

1

エラーはpush()の機能から発生します。 headがnullでない場合は、リストを最後のノードまで反復処理する必要があります。そして前に言われたように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; 
}