【发布时间】: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 tostderr`。
标签: c data-structures linked-list insertion