这个想法是当用户输入“1”时能够在链表的末尾添加名称,并在用户输入“0”时打印并删除链表中的第一个名称。如果链接列表中只有2个名称但是只有2个名称只有名字和姓氏,但是我看不到我的错误。
#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 :(得分: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
}
}
}