2017-10-30 4 views
0

今日はリンクリストを学び、このコードを試しました。 forループを使用して5つの入力値をリストに追加したかったのです。 forループの最後に、 "head = head-> next" は、リスト内の次のノードにヘッドポインタを進め、ループが終了すると、リストの最後のノードに.nextフィールドがNULLに設定されますリストの最後とwhileループを使用してリストを出力します。しかし、コードをコンパイルして実行すると、リストの出力値は同じではありません!を入力値とする。私はここでどこが間違っていますか?出力がノード内のすべてのデータ要素と等しくなるようにコードを変更するにはどうすればよいですか?

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

    struct node{ 
    int data; 
    int key; 
    struct node* next; 
    }; 

    struct node* head=NULL; 


    int main(){ 

    int i; 
    int a; 
    int b; 
    head=(struct node*)malloc(sizeof(struct node));//allocated memory 

    for(i=0;i<5;i++){ 
    scanf("%d %d",&a,&b); 
    head->data=a; 
    head->key=b; 
    head->next=(struct node*)malloc(sizeof(struct node)); 
    head=head->next; 
    } 
    head->next=NULL; 

    int j; 
    struct node* m; 
    m=head; 


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

     } 

    } 
+1

挿入プロセスに問題があります。 –

+0

Youiは頭にポインタを置き、テールを伸ばさなければなりません。あなたがしているのは、挿入した最後の有効な要素へのポインタを保持することです。 – Croolman

+0

ありがとうございます。しかし、私は正しい出力を得るために何をする必要があるのか​​混乱していますか? – Tanzim

答えて

0

は、以下のコードでは、私のコメントを参照してくださいとあなたの過ちを理解しよう。これは、リンクリストを作成してノードを追加する方法でもありません。

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

struct node{ 
int data; 
int key; 
struct node* next; 
}; 

struct node* head=NULL; 


int main(){ 

int i; 
int a; 
int b; 
head=(struct node*)malloc(sizeof(struct node));//allocated memory 
//above you have create a node and head is pointing to it 
for(i=0;i<5;i++){ 
    scanf("%d %d",&a,&b); 
    head->data=a; 
    head->key=b; 
    head->next=(struct node*)malloc(sizeof(struct node)); 
    //till above code it was find 
    head=head->next;//but here you did the mistake, now head it pointing to the newly created node and you lost the address of first node 
    //finally when you created the list with 5 nodes head is actually pointing to the last node of the list 
    //hence it will print only the last node of the list 
} 
    //now do some modification and rewrite the for loop like below 
/* 
struct node* p=head; 
for(i=0;i<5;i++){ 
    scanf("%d %d",&a,&b); 
    p->data=a; 
    p->key=b; 
    p->next=(struct node*)malloc(sizeof(struct node)); 
    p=p->next 
} */ 

// head->next=NULL; //also change this line with below line of code 
    p->next = NULL;  
int j; 
struct node* m; 
m=head; 
    while(m!=NULL){ 
     printf("%d %d ",m->data,m->key); 
     m=m->next; 
    } 
} 
1

これは、リンクリストの末尾に挿入を行う方法である:

void insertend(int a,int b) 
     { 
      current=head; 
      struct list * temp=(struct list*) malloc(sizeof(list)); 
      temp->data=a; 
      temp->key=b; 
      temp->next=NULL; 
      while(current->next!=NULL) 
      current=current->next; 
      current->next=temp; 
      current=temp; 
     } 
関連する問題