gpt4 book ai didi

c - 用递归方法遍历链表

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

我需要通过递归 void 函数来遍历由函数中间链接的列表,该函数的参数是三重指针。

程序如下

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

void insert(Node** first,int d){
Node* new= createNode(d);
new->next= *first;
*first=new;
}

Node* createNode(int d){
Node* new= (Node*)malloc(sizeof(Node));
new->data= d;
new->next=NULL;
return new;
}


void printList(Node***p)
{
Node**temp = *p;

if(temp == NULL)
return;
else
{
printf("\nValue: %d", (*temp)->data);

*temp = (*temp)->next;

printList(&temp);
}
}

int main()
{
Node *first = NULL;

int n =10;

while(n>0){
insert(&first,n);
n=n-1;
}

Nodo **ptr_first= &first;

printList(&ptr_first);

return 0;
}

该函数打印所有值,但程序挂起并返回负值。这个实现有什么问题吗?PD:三重指针的使用仅用于教学目的

最佳答案

你的递归终止条件是错误的。

您必须将 if(temp == NULL) 更改为 if(*temp == NULL),因为 *temp 指向到元素而不是 temp

我还认为,如果使用三重指针,对教学不利,因为这里不需要它们。

关于c - 用递归方法遍历链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51548778/

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