C 程序 - 链表问题

标签 c linked-list

我有一个模拟文本编辑器的程序。它允许用户根据发送的命令以他们选择的任何特定方式将文本行添加到列表中。

其中一个功能允许用户在列表中向后移动以查看他们的线路(还有另一个功能可以让他们向前移动,但那个功能没有问题)。

还有一些功能可以让用户插入或附加文本。 Insert 将该行放在当前行之前,而append 将其设置在当前行之后。我遇到的一个问题是插入文本的方式。

用户点击i进行插入,通过标准输入(stdin)输入文本,然后点击CTRL + D(在Linux环境)模拟NULL并返回命令模式。之后,如果您浏览列表,似乎会输入列表顶部的最后一行,并且所有内容都会向后跟随。有一次,我插入了 4 行文本,它对最后 2 行进行了无限循环,并破坏了文本文件。

我相信这与我链接列表的逻辑有关,但我很难将它们可视化。以下是有问题的函数:

void insert_line(char *t)
{
    /* Allocate and clear (i.e. set all to 0) */
    struct line *new_line = calloc(1, sizeof(struct line));

    new_line->text = t;

    if(current_line == NULL)
        head = current_line = new_line;
    else
    {
        new_line->prev = current_line->prev;
        new_line->next = current_line;
        current_line->next = new_line;
        current_line = new_line;

        if(current_line->prev == NULL)
            head = current_line;
    }
}

这一定是非常困惑的 - 它有时会无限循环文本并且总是将文本向后放置。这就是我使用 insert 函数的方式:

else if(command[0] == 'i')
    {
        char * line;
        while((line = get_line(stdin)) != NULL)
            insert_line(line);
     }

get_line 一次读取一行文本并返回,直到到达 EOF。我知道 get_line 函数正在运行,因为我的导师编写了它供我们使用。

//
// Function: previous_line
// Moves the current_line pointer to the previous node, if any, in the linked-list.
//
void previous_line(void)
{
    if(current_line == NULL)
        printf("Error: No Lines Exist.\n");
    else if(current_line->prev != NULL) {
        current_line = current_line->prev;
        printf("%s\n", current_line->text);
    }
    else
        printf("Error: Already beginning-of-line.\n");
}

这个很奇怪,当我在文本中间附加文本时,next_line 函数工作正常,但是当我运行它返回列表时,它没有显示我想要的内容已添加。

最佳答案

在纸上画出来(每行一个框,下一个和上一个箭头)

这部分有问题 - 当你绘制它时应该相当清楚。

new_line->prev = current_line->prev;
new_line->next = current_line;
current_line->next = new_line;
current_line = new_line;

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

相关文章:

c - 项目帮助 : Function and Struct issues in C?

Char 与 unsigned char 转换为 int

c - 分配通过pthread计算的值

c - 如何在不转到下一行的情况下在 C 中使用 printf() 和 scanf()?

c++ - 关于链表的指针问题

c - 在c中将节点插入链表

c - 链表和指针指向正确吗?

c - 指针分配二维数组指针的警告消息

c - 我在哪里可以学习链接列表/堆栈?

在 C 中的链表中创建链接