所以我认为发生的事情是我的头节点一直被覆盖,但我不确定为什么。如果我删除while循环并只是输入类似的东西它就可以了。
head = addItem(head, "item one");
head = addBack(head, "item two");
print(head);
这是现在的代码,下面我将包含带有函数的头文件。请注意我的所有菜单项目都不在循环中,现在已经停留在获取链接列表一段时间了。提前感谢任何提示或建议。
主:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "functions.h"
int menu();
void print(node *head);
node* addItem(node *head, char *item);
node* addBack(node *head, char *item);
int main()
{
int selection;
char *item;
node* head = NULL;
char junk;
// Run the menu, and do something based on the selection
do {
selection = menu();
// If they choose a number that's not between 1 and 3, or 0
if (selection > 3) {
printf("Please select a valid option\n");
}
// If they enter 1, add an item to the list
else if (selection == 1) {
printf("Enter your list item: ");
// scanf leftover characters so fgets will work
scanf("%c", &junk);
fgets(item, 100, stdin);
if (head == NULL) {
head = addItem(head, item);
}
else if (head != NULL) {
addBack(head, item);
}
}
else if (selection == 3) {
// Print remaining items
print(head);
}
} while (selection != 0);
return 0;
}
编辑:忘记在头文件中添加功能。
struct node
{
char *item;
struct node *next;
};
typedef struct node node;
// Menu of choices, returns selection
int menu()
{
int selection;
printf("\nChoose an option:\n1: Enter a list item \
\n2: Delete a list item\n3: Print remaining items \
\n0: Quit\n\n");
scanf("%d", &selection);
return selection;
}
node* addItem(node *head, char *item)
{
node *tmp;
tmp = malloc(sizeof(node));
tmp->item = item;
tmp->next = head;
head = tmp;
return head;
}
node* addBack(node *head, char *item)
{
node *tmp, *p;
tmp = malloc(sizeof(node));
tmp->item = item;
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = tmp;
tmp->next = NULL;
return head;
}
void print(node* head)
{
node *tmp;
tmp = head;
if (tmp == NULL) {
printf("Add an item first, list is empty\n");
exit(0);
}
while(tmp != NULL)
{
printf("%s\n ", tmp->item);
tmp = tmp->next;
}
}
答案 0 :(得分:1)
您使用具有自动存储时间item
的未初始化变量值来调用未定义行为,这是不确定的。
在读取输入之前分配足够的缓冲区。
else if (selection == 1) {
printf("Enter your list item: ");
// scanf leftover characters so fgets will work
scanf("%c", &junk);
/* add from here */
item = malloc(100);
if (item == NULL) {
perror("malloc");
return 1;
}
/* add until here */
fgets(item, 100, stdin);
if (head == NULL) {
head = addItem(head, item);
}
else if (head != NULL) {
addBack(head, item);
}
}