gpt4 book ai didi

c - C中的链表实现(只打印最后两个节点)

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:01 26 4
gpt4 key购买 nike

#include <stdlib.h>
#include <stdio.h>

struct node {
int data;
struct node *next;
};
void addLast(struct node **head, int value);
void printAll(struct node *head);
struct node *head1 = NULL;

int main() {
addLast(&head1, 10);
addLast(&head1, 20);
addLast(&head1, 30);
addLast(&head1, 40);

printAll(head1);

return 0;
}

void addLast(struct node **head, int value) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = value;
if (*head == NULL) {
*head = newNode;
(*head)->next = NULL;
} else {
struct node **temp = head;

while ((*temp)->next != NULL) {
*temp = (*temp)->next;
}
(*temp)->next = newNode;
newNode->next = NULL;
}
}

void printAll(struct node *head) {
struct node *temp = head;
while (temp != NULL) {
printf("%d->", temp->data);
temp = temp->next;
}
printf("\n");
}

addLast() 将在列表末尾 append 新节点,使用 printAll(),我正在打印整个列表。

每次打印列表时,我只能看到最后两个节点。

谁能帮忙,为什么循环没有遍历整个列表?

最佳答案

函数 addLast 太复杂了,结果因为这条语句是错误的

*temp = (*temp)->next;

在 while 循环中。它总是改变头节点。

按如下方式定义函数

int addLast( struct node **head, int value )
{
struct node *newNode = malloc( sizeof( struct node ) );
int success = newNode != NULL;

if ( success )
{
newNode->data = value;
newNode->next = NULL:

while( *head ) head = &( *head )->next;

*head = newNode;
}

return success;
}

请注意,无需将变量 head1 声明为全局变量。最好在函数 main 中声明它。

此外,在退出程序之前应释放所有分配的内存。

关于c - C中的链表实现(只打印最后两个节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com