簡體   English   中英

C程序-鏈表問題

[英]C Program - Linked List Problems

我有一個模擬文本編輯器的程序。 它使用戶可以根據他們發送的命令以任何特定方式將文本行添加到列表中。

其中一個功能使用戶可以在列表中向后移動以查看其行(還有另一個功能可以使他們向前移動,但是這並不成問題)。

還有讓用戶插入或附加文本的功能。 插入在當前行之前插入行,而插入在當前行之后設置行。 我遇到的一個問題是插入文本的方式。

用戶按下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;

如果您嘗試將換行符追加到文本文件中,則應該這樣做

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

current_line = new_line;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM