gpt4 book ai didi

c - C 中的链表实现

转载 作者:行者123 更新时间:2023-11-30 21:14:42 26 4
gpt4 key购买 nike

所以我开始学习数据结构,并轻松地用 Java 和 Python 成功实现了 LinkedList。但我的 C 代码有些不对劲,我没有得到输出。这个指针概念确实困扰着我,如果有人能告诉我我在这个实现中的错误,我将不胜感激。

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

struct node
{
int data;
struct node *next;
};

void append(int data, struct node *head, struct node *tail){
struct node *newNode = ((struct node*)malloc(sizeof(struct node)));
(*newNode).data = data;
(*newNode).next = NULL;
if (head == NULL)
{
head = newNode;
tail = newNode;
}else{
tail -> next = newNode;
tail = newNode;
}

}

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


int main()
{
printf("Hey linked list \n");
struct node *head = NULL;
struct node *tail = NULL;
/* code */
append(3,head,tail);
append(4,head,tail);
append(5,head,tail);
traverse(head);
return 0;
}

顺便说一句,就像 head 总是指向链表中的第一个节点一样,我有一个指针 tail 总是指向链表中的最后一个节点。通过这种方式将数据追加到列表中很容易并且时间恒定。

谢谢你们,我希望得到一个易于理解的答案..

最佳答案

您的 headtail 指针未按您的预期设置。 c 中的所有内容都是按值传递的,因此本质上传递给函数的所有参数都是局部变量,其作用域仅在该函数内。当您将 headtail 传递给 append 时,会创建每个文件的本地副本。您对 headtail 进行了赋值,但是一旦函数退出并且变量超出范围,这些赋值就会丢失。如果您希望赋值“粘”在函数外部,则必须将这些指针的地址传递给 append 并在那里取消引用它们。

void append(int data, struct node **head, struct node **tail)
{
struct node *newNode = ((struct node*)malloc(sizeof(struct node)));
(*newNode).data = data;
(*newNode).next = NULL;
if (head == NULL)
{
*head = newNode; // dereference head here so this assignment will persist outside of this function
*tail = newNode;
}else{
(*tail) -> next = newNode;
*tail = newNode;
}
}

.....

int main(void)
{
printf("Hey linked list \n");
struct node *head = NULL;
struct node *tail = NULL;
/* code */
append(3,&head,&tail);
append(4,&head,&tail);
append(5,&head,&tail);
traverse(head);
return 0;
}

关于c - C 中的链表实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575631/

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