【发布时间】:2018-02-21 01:08:43
【问题描述】:
在这张图片中,我必须编写一个程序,每次读取字母i时,它都会将后面的值插入到链表中。如果它到达有两个数字ex:i 23 42的行,它将在23之后将42输入到链表中。
所以如果我将链表打印到 txt 文件的第 3 行,它应该打印23, 78, 900。当它到达第四行时,它应该打印23, 42, 78, 900。
我不确定如何让程序识别行中有两个值而不是一个,以便能够将第一个值之后的第二个值输入到链接列表中。
编辑**
struct node * addToList(struct node *base, int data)
{
struct node *newNode = NULL;
if (base == NULL)
{
base = malloc( sizeof(struct node));
// malloc defend
base->data = data;
base->next = NULL;
return base;
}
while (base->next != NULL)
{
base = base->next;
}
//Now at the end of the list
newNode = malloc( sizeof(struct node));
//Defend against bad malloc
base->next = newNode;
newNode->data = data;
newNode->next = NULL;
return base;
'下一部分在 main'
while (fscanf(ifp, "%s", inBuf) != EOF)
{
fprintf(stdout, "%s\n", inBuf);
data = atoi(inBuf);
if (NULL == root)
{
root = addToList(root, data);
}
else
{
temp = addToList(root, data);
if (NULL == temp)
{
printf("Failed to add - good bye\n");
return -1;
}
}
我正在尝试创建一个新函数来处理插入
【问题讨论】:
-
你能告诉我们你到目前为止所做的尝试吗?
-
链表的实现有这么多,我们怎么知道你用的是哪一个呢?请发布代码,最好发布minimal reproducible example
-
这是解析的基本问题。也许在谷歌上搜索一些解析示例?
-
欢迎来到 Stack Overflow。请注意,在这里说“谢谢”的首选方式是投票赞成好的问题和有用的答案(一旦你有足够的声誉这样做),并接受对你提出的任何问题最有帮助的答案(这也给出了你的声誉小幅提升)。请查看About 页面以及How do I ask questions here? 和What do I do when someone answers my question?
-
一行中可能有超过 2 个数字吗?如果它们的数量可以是任意数量,那么您需要使用
fgets()或 POSIXgetline()来读取行,然后按照 Usingsscanf()in loops 中的指南从字符串中读取数字。
标签: c list linked-list