gpt4 book ai didi

c - 通过递归函数打印链表的节点

转载 作者:行者123 更新时间:2023-11-30 17:18:25 25 4
gpt4 key购买 nike

我被要求使用 C 语言制作几个程序。在其中一个程序中,我需要创建一个链接列表,以便我可以用它做一些事情。但是,我不允许在任何这些程序中使用全局变量或循环(While、For 等)。所以这是我编写的一个小程序,只是为了刷新链接列表:

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

struct node {

int number;
struct node *next;

};

void create (struct node *, struct node *);
void insert (struct node *, struct node *);
void display (struct node *);

int main(void) {

struct node *head;
struct node *current;
struct node *temp;

create ( head, current );

insert ( head, current );

temp = head;

display ( temp );

}

void create ( struct node *head, struct node *current ) {

int a;

printf("Insert: ");
scanf("%d", &a);
current = malloc(sizeof(struct node));
current -> number = a;
current -> next = NULL;
head = current;

}

void insert ( struct node *head, struct node *current ) {

int b;

printf("insert: ");
scanf("%d", &b);

if ( b == -1 ) return;
else {

current = malloc(sizeof(struct node));
current -> number = b;
current -> next = NULL;

}

insert ( head, current );

}

void display ( struct node *temp ) {

if ( temp != NULL ) {

printf("%d \t", temp -> number); //Error: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
temp = temp -> next;

display ( temp );

}
else return;

}

这或多或少是每本书都有的标准代码,但我使用递归函数代替循环。如果你仔细观察,我发现 display() 函数有问题。我在函数内的 printf() 行收到此错误:EXC_BAD_ACCESS (code=EXC_I386_GPFLT)。所以我无法在屏幕上打印我的列表。我已经调试了大约 4 个小时,但我找不到问题所在,任何帮助将不胜感激!

最佳答案

风向标发布的问题之上的第三个问题:

你的插入内容很奇怪。您要求输入,然后再次递归调用插入。寻求意见,...但你永远不会在链表的链中 Hook 当前的内容。

关于c - 通过递归函数打印链表的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175375/

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