這個想法是,當用戶輸入「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;
}
}
「*我們的想法是能夠將名稱添加到鏈接列表的末尾... *」 - 跟蹤鏈表末尾的變量在哪裏? –
如果您將'temp-> next'設置爲null,然後在頭後添加它,則會丟失列表的其餘部分。 –
我認爲問題是頭部和尾部都使用相同的頭部變量。所以添加名稱添加節點在head-> next應該是tail-> next –