gpt4 book ai didi

c - 程序更新链表

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:59 28 4
gpt4 key购买 nike

我正在尝试创建一个带有名称的链表,例如:

Tom -> David -> John...

在我的 main 函数中,我有一个 switch 菜单,程序会在其中询问您是要创建新列表还是退出。

当用户选择1 时,程序调用insertIntoLinkedList(name, &head) 函数,用户可以在其中添加名称或键入“end”退出。

一切正常,但是如果用户输入 end 并再次选择选项 1,程序会创建一个新的 linked list 而我想要将名称添加到现有列表。

有人可以帮我解决我的问题吗?感谢您的宝贵时间。

编辑

这是我的源代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define NAME_SIZE 30
#define EXIT "end"

// Node structure
struct node {
char name[NAME_SIZE];
struct node *next;
};

typedef struct node Node;
typedef struct node* NodePointer;

int userChoice(void);
void insertIntoLinkedList(char [], NodePointer *);
void displayNames(NodePointer);

int nodeCounter = 0;

int main(void) {
int choice = 99;

do {
printf("\n--- MENU ---\n\n");
printf("1.\tCreate a new friend list\n");
printf("2.\tExit o_O");
printf("\n\n------------\n");
printf("Go to:\t");
choice = userChoice();

switch (choice) {
case 1: {
char name[NAME_SIZE] = "";
NodePointer head = NULL;
while(0 != strcmp(name, EXIT)){
printf("Enter new friend name or \"%s\" to return back to the main menu: ", EXIT);
scanf("%s", name);
if(0 != strcmp(name, EXIT)){
insertIntoLinkedList(name, &head);
displayNames(head);
}
}
displayNames(head);
break;
}
case 2: {
printf("\n\nYou have %d node(s) in your linked list. Have a great day.\n\n", nodeCounter);
break;
}
default:
printf("There is no such option. Please choose one of the option from 1 to 2.\n");
}
} while(choice != 2);


return 0;
}

int userChoice() {
int num;
scanf("%d", &num);
return num;
}

void insertIntoLinkedList(char word[], NodePointer *head){
NodePointer newNode = NULL;
NodePointer previous = NULL;
NodePointer current = *head;

newNode = malloc(sizeof(Node));
if(NULL != newNode){
strcpy(newNode -> name, word);
while(NULL != current && strcmp(word, current -> name) > 0){
previous = current;
current = current -> next;
}

if(NULL == previous){
newNode -> next = current;
*head = newNode;
} else {
previous -> next = newNode;
newNode -> next = current;
}
}
}

void displayNames(NodePointer current) {
nodeCounter = 0;
if(NULL == current){
printf("Friend list is empty... I am sorry :(\n\n");
return;
} else {
printf("\nCurrent friend list: ");
while(NULL != current){
nodeCounter++;
printf("%s → ", current -> name);
current = current -> next;
}
printf("\nNumber of friends in your current list:\t%d\n\n", nodeCounter);
}
}

最佳答案

好吧,你可以为此声明一个新函数。因为每次调用这个函数时,head 都会被重新声明。

E.g case 3:printf("\nEnter A New Friend Name:\n");
scanf("%s",name);
insertIntoLinkedList(name, &head);
displayNames(head);
break;

关于c - 程序更新链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799223/

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