我正在使用此append函数将数据追加到链接列表中,但未显示任何输出。我已经多次审查了代码。该代码在我之前的代码中有效。
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
我应该在链接列表管理中进行更改吗?
答案 0 :(得分:3)
问题仅在于在printList()
中打印出来:
while(node->next!=NULL)
最后一个节点具有值5
和node->next == NULL
,因此循环将终止而不进行打印。只需更改为:
while(node != NULL)