2016-09-28 7 views
-3

にリンクリストを作成していませんリンクリストが正常に作成されていて、構造体へのグローバルポインタとしてnode *headを使用し、をhead(アドレスはnode *head)と置き換え、LinkedList *list(関数の引数に)をnode *headに置き換えた場合、 headnode *headのアドレス)の代わりにlist->headまたはlistを使用し、と宣言した場合の語はnode *headであり、リンクされたリストに値を入力しますが、リンクされたリストは表示しません。プログラムはとても私を助けてください、私はリンクリストで苦手リンクされたリストが表示されますが、C

問題の原因コードは以下の通りです:

#include<stdio.h> 
#include<malloc.h> 

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

typedef struct LinkedList_ 
{ 
    node *head; 
} LinkedList; 


void create(LinkedList *list){ 

    char choice='y'; 
    do{ 

     node *newnode,*temp; 
     newnode=(node*)malloc(sizeof(node*)); 
     printf("\nenter the data: "); 
     scanf("%d",&newnode->data); 
     newnode->next=NULL; 
     if(list==NULL){ 
      list->head=newnode; 
      temp=newnode; 
     } 
     else{ 
      temp=list->head; 
      while(temp->next!=NULL){ 
       temp=temp->next; 
      } 
      temp->next=newnode; 
     } 
     printf("\ndo you want to continue(y or no)? "); 
     choice=getche(); 

     }while(choice=='y'); 
} 


void display(LinkedList *list){ 
    printf("\n["); 
    while(list->head!=NULL){ 
      printf("%d,",list->head->data); 
      list->head=list->head->next; 
    } 
    printf("]"); 
} 


void main(){ 
    LinkedList *head=NULL; 
    create(head); 
    display(head); 
} 
+1

「もしあればstackoverflowののルール/ポリシーに精通していません」 - 11ヶ月後にあなたは[ツアー]を撮って[尋ねる]必要があります。 – Olaf

+0

これは私の2回目または3回目の質問を投稿するもので、よくスタックオーバーフローを訪れません。 –

+1

Ignorantia legis non excusat – Olaf

答えて

2

修正のように、この

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

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

typedef struct LinkedList_ { 
    node *head; 
} LinkedList; 

void create(LinkedList *list){ 
    char choice='y'; 
    if(!list || list->head){//guard 
     fprintf(stderr, "Invalid call %s.\n", __func__); 
     return; 
    } 

    node *temp; 
    do{ 
     node *newnode; 
     newnode = malloc(sizeof(*newnode));//or malloc(sizeof(node)); 
     printf("\nenter the data: "); 
     scanf("%d", &newnode->data); 
     newnode->next = NULL; 
     if(list->head == NULL){ 
      list->head = newnode; 
      temp = newnode; 
     } else { 
      temp = temp->next = newnode;//There is no need to follow the link 
     } 
     printf("\ndo you want to continue(y or no)? "); 
     choice=getche(); 
    }while(choice=='y'); 
} 


void display(LinkedList *list){ 
    node *curr = list->head;//head should not be changed 
    printf("\n["); 
    while(curr != NULL){ 
      printf("%d,", curr->data); 
      curr = curr->next; 
    } 
    printf("]\n"); 
} 

int main(void){ 
    LinkedList head = { NULL };//requires entity 
    create(&head); 
    display(&head); 
} 
関連する問題