【问题标题】:Append (add to tail) of linked list function in C is printing incorrectly (does not print out last element appended)C 中链表函数的附加(添加到尾部)打印不正确(不打印附加的最后一个元素)
【发布时间】:2018-09-19 16:45:40
【问题描述】:

这是我的第一篇文章,如果我的帖子有任何错误,请指出。

这是一个 c 赋值,它从文本文件中获取命令(例如 Push、Head、Append 等),然后对链表执行相应的操作。我有一个头文件,一个包含我的主类的 c 文件和一个带有链表函数的 c 文件。

我的所有函数都正常工作,即我的 remove()、push()、printlist()、head() 和 tail(),除了我的 append(添加到列表末尾)函数。

这是我在头文件中的结构:

typedef struct node 
{
    char data;
    struct node * next;
} node_t;

这是我的附加功能:

node_t * append(node_t ** headRef, char data)
{
    node_t * current = *headRef;
    node_t * newNode;
    newNode = malloc(sizeof(node_t));
    newNode->data = data;
    newNode->next = NULL;
    // special case for length 0
    if (current == NULL) {
        *headRef = newNode;
    }
    else 
    {
        // Locate the last node
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }   
}

我的打印方法(如有必要):

void print_list(node_t * head)
{
    node_t * current = head;
    if(current->next == NULL)                       /* IF no elements in list, */
    {
        printf("-\n");                          /* Print empty hyphen and new line*/
        return;
    }
    else 
    {
        while (current->next != NULL)               
        {
            if(current->next->next ==NULL)              /* Otherwise if there are is one element */
                printf("%c\n", current->data);          /* Print character and a new line (last character) */
            else if (current->next==NULL)               /* Otherwise if there are is more than one element */
                printf("%c-\n", current->data);         /* Print character and hyphen between characters) */
            else
                printf("%c-", current->data);
            current = current->next;                /* Move on to next element in list */
        }
    }
}

最后这是我的主要外观:

    int main(int argc, char *argv[])
    {
        node_t * test_list = (node_t *)malloc(sizeof(node_t));

        FILE * fp;                          
        fp = fopen(argv[1], "r");
        char line[20];
        int lngth;

        while(fgets(line, 20, fp)!=NULL)                /* Loop to read every command in each file */
        {
            line [ strcspn(line, "\n") ] = 0;               /* Removes all nextline characters from array */

            //Here, I just get conditionals for the statement in the testfile
            //............
            else if(strncasecmp(line, "Append",4) ==0)      /* Check if line matches instruction 'Append' regardless of casing */
            {
                if(strncmp(line, "Append",4) ==0)       /* Now check if the line matches with casing */
                {
                    char letter = line[7];          /* If yes extract the alphabetical character to append */
                    append(&test_list, letter);
                }
                else                        /* If line casing not correct, output to stderr */
                    fprintf (stderr, "Input not valid\n");  
            }   

            else if(strcmp(line, "PrintList") ==0)          /* Check if line matches instruction 'PrintList' */
                print_list(test_list);              /* If it does, print out the list */
            //more conditionals
            //.........
            else                            /* Triggers if line does not match any above instructions */
                fprintf (stderr, "Input not valid\n");      /* Outputs to stderr */
        }
        fclose(fp);
   }

看起来我在链表中​​的第一个元素为 0(空白空间将打印 printf("%c",node->data) 用于未分配的字符

测试用例示例:

Input:
    Append A
    PrintList

Outputs:
    (Blank line)

如前所述,所有其他功能都可以正常工作,并且在打印时,如果存在 A B 和 C 的 3 个元素并且当列表为空时为空连字符 (-),则看起来像 A-B-C。

测试用例 2 示例:

Input:
    Append A
    Append B
    Append C

Outputs:
    -A-B

请指出我的逻辑有缺陷的地方。我怀疑我的头最初不是空的,但是将其设置为空会导致我的其他方法无法正常工作,并且也无助于追加。

一些研究还表明,例如,如果我最初将 head 设置为“z”,则测试用例 1 的 append 输出将为 z,测试用例 2 的输出将为 z-a-b

我的主要问题是为什么我的附加功能不能与我的打印功能一起正常工作,因为它并没有简单地附加我所有的元素。

我在 ubuntu 64 位系统上使用 gcc 进行编译。

【问题讨论】:

  • 重做 print_list 循环以使用 while (current != NULL) 而不是 while (current->next != NULL)
  • append() 应该没问题,只要malloc() 成功......但print_list() 需要工作。记住current->nextNULL 最后一个节点current->next->nextNULL 倒数第二个节点

标签: c linked-list append


【解决方案1】:

感谢 500 - Internal Server Error 和 Dmitri。

问题就这么简单。我只是认为我的 print 方法可以正常工作是因为其他功能,而没有看到我实际上一直在解决这个问题并且在我的列表中有一个额外的元素。

我通过更改我的 print_list 方法来修复它,如下所示:

void print_list(node_t * head)
{
    node_t * current = head;
    if(current == NULL)                     /* IF no elements in list, */
    {
        printf("-\n");                          /* Print empty hyphen and new line*/
        return;
    }
    else 
    {
        while (current != NULL)                 
        {
            if (current->next==NULL)        
                printf("%c\n", current->data);
            else
                printf("%c-", current->data);
            current = current->next;                /* Move on to next element in list */
        }
    }
}

然后我也可以依次将我的 head 在 main 中初始化为 null:

node_t * test_list = NULL;

而不是:

node_t * test_list = (node_t *)malloc(sizeof(node_t))

因为我想要一个空列表以便我的边界可以正常工作并且我打印出最后一个元素,因为旧循环 current->next != NULL 在 NULL 处停止并且不会打印出我的最后一个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2018-04-22
    • 1970-01-01
    • 2019-04-27
    • 2012-12-13
    • 2020-05-31
    相关资源
    最近更新 更多