gpt4 book ai didi

c - 链表创建函数任意添加节点

转载 作者:行者123 更新时间:2023-11-30 15:44:24 26 4
gpt4 key购买 nike

我有一个 C 函数,应该为链表创建 3 个节点。问题是该函数似乎添加了一个额外的节点,而我无法发现我的错误。有人可以看一下输出和代码并让我知道我的错误是什么吗?难道是虚拟机编译环境的问题?我在运行 BackTrack Linux 的虚拟机中使用以下代码进行编译:

gcc link.c -o link

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DELIMITER ,

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

struct node* create()
{
//define head pointers
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;

//allocate memory
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));

//setup fields
//assign links
head->data = 15;
head->next = second;

second->data = 20;
second->next = third;

third->data = 25;
third->next = NULL;

return head;
}

int main(int argc, const char *argv[])
{
int size;
struct node *head;

head = create();

struct node *curr = head;

while(curr->next != NULL)
{
printf("%d\n", curr->data);
curr++;
}

return 0;
}

这是输出:

15 0 20 0

最佳答案

使用链表时,curr++ 不像在标准数组中那样工作。链表的全部要点是列表中的数据不是连续的。您不能简单地增加 curr 并期望它指向列表中的下一个元素,因为 malloc 不 promise 顺序调用将返回内存顺序单元的地址。

您要找的是

curr = curr->next;

但是,这还需要您修改循环。由于 curr->next 将在最后一个节点之前的一个节点为 NULL,因此将跳过最后一个元素。你的状况

curr->next != NULL

经过上述调整后,应该是

curr != NULL

此外,malloc 返回空指针,虽然没有必要,但我认为您应该将它们转换为正确的指针类型。

 //allocate memory
head = (struct node*) malloc(sizeof(struct node));
second = (struct node*) malloc(sizeof(struct node));
third = (struct node*) malloc(sizeof(struct node));

关于c - 链表创建函数任意添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484541/

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