【问题标题】:Why my append function is not showing output?为什么我的附加功能没有显示输出?
【发布时间】:2020-04-15 23:38:45
【问题描述】:

我正在使用这个附加函数在我的链表上附加数据,但它没有显示任何输出。我已经多次查看代码。此代码在我之前的代码中有效。


void append(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    struct Node *last = *head_ref;  /* used in step 5*/

    /* 2. put in the data  */
    new_node->data  = new_data;

    /* 3. This new node is going to be the last node, so make next
          of it as NULL*/
    new_node->next = NULL;

    /* 4. If the Linked List is empty, then make the new node as head */
    if (*head_ref == NULL)
    {
       *head_ref = new_node;
       return;
    }

    /* 5. Else traverse till the last node */
    while (last->next!= NULL)
        last = last->next;

    /* 6. Change the next of last node */
    last->next = new_node;
    return;
}

void printList(struct Node *node)
{
while(node->next!=NULL)
{
printf("%d ",node->data);
node = node->next;
}
}

int main()
{
struct Node *head = NULL;

push(&head,7);
push(&head,1);
push(&head, 3);
push(&head, 2);
append(&head,5);

puts("Created Linked List: ");
printList(head);
//deleteNode(&head, 1);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}

它正在输出: 2->3->1->7 虽然我需要输出: 2->3->1->7->5

我应该对链表管理进行更改吗?

【问题讨论】:

  • 欢迎来到 StackOverflow。你也调试过你的代码吗?
  • OT: about: struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 1) 在C语言中,返回类型为void*,可以赋值给任意指针。强制转换只会使代码混乱。建议去掉演员表。 2) 在调用任何堆分配函数时:malloc()calloc() 和/或realloc(),始终检查 (!=NULL) 返回值以确保操作成功。如果不成功,则调用perror( "my error message" ); to output both your error message AND the text reason the system thinks the error occurred to stderr`。

标签: c data-structures linked-list insertion


【解决方案1】:

问题只是在printList() 中打印出来:

while(node->next!=NULL)

最后一个节点的值为5node->next == NULL,因此循环将终止而不打印。只需更改为:

while(node != NULL)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2019-12-21
    相关资源
    最近更新 更多