这个想法是能够在用户输入“ 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 - 无法在我的代码中找到错误? C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43484600/

10-11 21:54
查看更多