gpt4 book ai didi

在我的代码中找不到错误? C

转载 作者:行者123 更新时间:2023-11-30 19:34:44 25 4
gpt4 key购买 nike

这个想法是能够在用户输入“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;
}
}

最佳答案

第一个错误:

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
}
}
}

关于在我的代码中找不到错误? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43484600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com