2017-04-19 62 views
-1

這個想法是,當用戶輸入「1」時,能夠在鏈表的末尾添加一個名字,當用戶輸入「0」時,打印並刪除鏈表中的名字。如果在鏈表中只有2個名字但是不能超過2個名字,那麼這是行得通的,但是我看不到我的錯誤。在我的代碼中找不到錯誤? C

#include<stdio.h> 
#include<stdlib.h> 
#include<conio.h> 
#define bool int 
#define TRUE 1d 
#define FALSE 0 

typedef struct node{ 
    char name[100]; 
    struct node *next; 
} Node; 

Node *head; 

void call(){ 
    if(head == NULL){ 
      printf("List is empty.\n"); 
     } 
     else{ 
      Node *temp; 
      printf("Calling %s\n", head->name); 
      if(head->next!=NULL){ 
       temp = head->next; 
       free(head); 
       head = temp; 
      } 
      else{ 
       head = NULL; 
      } 
     } 
} 

void add(char input[]){ 
     Node *temp; 
     temp = (Node*)malloc(sizeof(Node)); 
     strcpy(temp->name, input); 
     temp->next = NULL; 
     if(head == NULL){ 
      head = temp; 
     } 
     else{ 
      head->next = temp; 
     } 
} 

int main(){ 

    start:; 
    int user_menu_answer; 
    char waste; 

    printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n"); 
    printf("0) Call a customer\n"); 
    printf("1) Add a customer\n"); 
    printf("2) Quit\n"); 
    printf("Please input your command \n"); 
    printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n"); 
    scanf("%d%c", &user_menu_answer, &waste); 

    //main menu options 
    if(user_menu_answer == 0){ 
     call(); 
     goto start; 
    } 
    else if (user_menu_answer == 1){ 
     char input[23]; 
     printf("Please give me the customers name: \n"); 
     scanf("%[^\n]", input); 
     add(input); 
     goto start; 
    } 
    else if (user_menu_answer == 2){ 
     printf("Quitting..."); 
     return 0; 
    } 
    else{ 
     printf("You did not enter a valid option, Please try again. \n"); 
     goto start; 
    } 
} 
+0

「*我們的想法是能夠將名稱添加到鏈接列表的末尾... *」 - 跟蹤鏈表末尾的變量在哪裏? –

+1

如果您將'temp-> next'設置爲null,然後在頭後添加它,則會丟失列表的其餘部分。 –

+0

我認爲問題是頭部和尾部都使用相同的頭部變量。所以添加名稱添加節點在head-> next應該是tail-> next –

回答

0

的第一個錯誤:

void call(){ 

if(head == NULL){ 
     printf("List is empty.\n"); 
    } 
    else{ 
     Node *temp; 
     printf("Calling %s\n", head->name); 
     if(head->next!=NULL){ 
      temp = head->next; 
      free(head); 
      head = temp; 
     } 
     else{ 
      free(head); //you don't free the memory if it's just one in the list 
      head = NULL; 
     } 
    } 
} 

第二個錯誤:

void add(char input[]){ 
    Node *AuxHead; //create an aux to the head so you can move threw the list 
    Node *temp; 
    temp = (Node*)malloc(sizeof(Node)); 
if(temp!=NULL) //verify if it got allocated 
{ 
    strcpy(temp->name, input); 
    temp->next = NULL; 
    if(head == NULL){ 
     head = temp; 
    } 
    else{ 
     AuxHead=head; //pass the address of the head 
     while(AuxHead->next!=NULL) //catch the lest node of the list 
      AuxHead=AuxHead->next; 
     AuxHead->next = temp; //make the temp, the last of the list 
    } 
} 
} 
+0

上帝保佑你,先生! –

+0

CAn你對我的回答放棄了嗎?所以人們知道這個問題已經得到妥善解答。 – BlazeChill