2015-02-08 63 views
0

我正在嘗試讀取鏈接列表中的文本文件併成功顯示它。但是我一直通過在讀取函數中使用puts(id - > ...)參數來成功地讀取和打印文件中的一個對應於(head == NULL)的「List is Empty」消息但我不能像上面提到的那樣去顯示功能。通過文本文件讀取和顯示鏈接列表

struct node 
    { 
     char name[50]; 
     int id; 
     struct node *next; 
    } *head; 

    int main() 
    { 
     int i,num; 
     struct node *r; 
     head=NULL; 
     readfile(*r); 
     while (1) 
     { 
      printf("\nList Operations\n"); 
      printf("============\n"); 
      printf("1.Insert\n"); 
      printf("2.Display\n"); 
      printf("3.Delete by ID\n"); 
      printf("4.Delete by Name\n"); 
      printf("5.Exit\n"); 
      printf("Enter your choice: "); 

      if (scanf("%d", &i) <= 0){ 
       printf("Enter only an integer\n"); 
       exit(0); 
      } else { 
       switch(i) 
       { 
        case 1: 
         if(head==NULL) 
         { 
          printf("List is Empty\n"); 
         } 
         else 
         { 
          printf("Element in the list are: "); 
         } 
         display(r); 
         break; 
        case 2: 
         return 0; 
        default: 
         printf("Invalid Choice\n"); 
       } 
     } 
} 

void readfile(struct node *r) 
{ 
    r=head; 

    char str[50]; 
    int id; 
    FILE *ifp=fopen("One.txt","r"); 
    while (fgets(str,50,ifp)!=NULL){ 
     r =(struct node *)malloc(sizeof(struct node)); 
     char *token=strtok(str,","); 
     strcpy(r->name,token); 
     puts(r->name); 
     token=strtok(NULL,"\n"); 
     r->id=token; 
     puts(r->id); 
     r->next=NULL; 
     r=r->next; 
     } 
} 

void display(struct node *r) 
{ 
    r = head; 
    if(r == NULL) 
    { 
     return; 
    } 
    while(r != NULL) 
    { 
     printf("Student %s has id %d.\n", r->name,r->id); 
     r = r->next; 

    } 
    printf("\n"); 
} 

回答

0

在您提供的代碼中,您從未分配或分配任何東西給head。我想你需要添加以下代碼某處

if (head == NULL) { 
    head = r; 
} 

if (head == NULL) { 
    head = (struct node *)malloc(sizeof(struct node)); 
    // and initialize it with something 
} 

此外,我建議你創建喜歡add_node更一般的功能,這樣

void add_node(struct node *r) { 
    if(head == NULL) { 
     head = r; 
    } else { 
     struct node* n = head; 
     while(n->next != NULL) { // go to the end of the list 
     } 
     r->next = NULL; // to be sure this will be end of list 
     n->next = r; 
    } 
} 

然後在readfile讀取數據,創建新節點並將其傳遞給add_node