【发布时间】:2021-06-11 11:21:15
【问题描述】:
我是编程初学者。谢谢你帮助我。
我正在尝试在字符串中创建一个链接列表。 输入是字符串,如果输入是“退出”则结束。 但是当我编译它时,它只打印出最后的输入,我无法解决它! 从函数addrear中区分数据是否第一次存储在链表中。并适当地存储数据和链接到另一个节点。 从函数printlist开始,从链表的开头开始,打印出每个节点的数据。
我用整数类型尝试过,当这段代码用 int 而不是 string 执行时,它工作正常,所以我认为错误来自字符数组。
例如)输入1“转储”,
输入2“结束”,
输入3“目录”,
input4 "退出",
输出会是
转储, 结尾, 目录, 退出
但它出来了
退出 出口 出口 退出
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char instruction[1000];
struct Node {
struct Node* next;
char* data;
};
struct Node* pStart = NULL;
struct Node* pEnd = NULL;
void addrear(char* val)
{
struct Node* Current;
Current = (struct Node*)malloc(sizeof(struct Node));
Current->data = val;
Current->next = NULL;
//printf("%s\n", Current->data);
if (pStart == NULL)
{
pStart = Current;
pEnd = Current;
}
else
{
pEnd->next = Current;
pEnd = Current;
}
}
void printlist(struct Node* Current)
{
Current = pStart;
while (Current != NULL)
{
printf("%s\n", Current->data);
Current = Current->next;
}
}
int main()
{
int i;
while (1)
{
printf("sicsim> ");
fgets(instruction, sizeof(instruction), stdin);
instruction[strlen(instruction) - 1] = '\0';
addrear(instruction);
if (strcmp(instruction, "exit") == 0)
{
break;
}
}
printlist(pStart);
}
【问题讨论】:
-
't prints out last inputs only' 明白了...
-
“链表”标签下有一些 (!) 重复项。
标签: c string data-structures linked-list