gpt4 book ai didi

c - 向函数提供的参数变为 NULL?

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

我编写了一个递归函数来反转链表,如下所示:

struct node{
int val;
struct node *next;
};
//Global pointer to structure
struct node *start=NULL,*head=NULL;


//*Function to input node*

void create(int data){

struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(start == NULL){
temp->val=data;
temp->next=NULL;
start=temp;
head=temp;
}
else{
temp->val=data;
temp->next=NULL;
head->next=temp;
head=temp;
}
}

*Function to reverse the linked list*
void* rev(struct node *prev,struct node *cur){
if(cur!=NULL){
printf("Works");
rev(cur,cur->next);
cur->next=prev;
}
else{
start=prev;
}

}

main中相关代码为:

  main(){
struct node *temp;
temp=start;
/*Code to insert values*/
rev(NULL,temp);
}

现在代码接受输入并完美打印它,但是在我调用 rev() 函数之后,相同的遍历函数什么也不打印。我确实在调试器上逐行运行了代码,它给出了以下输出:

rev (prev=0x0, cur=0x0)

此外,由于 cur 在某种程度上为 NULL,因此 rev()if 部分永远不会被执行,只有 else 执行一次。当我在 create() 函数中获取输入时,我会将 start 更新为链表的第一个元素,甚至在 main 中,打印语句也证明了这一点。但是为什么函数 rev() 总是接收 NULL 的输入参数呢?

如果需要任何额外信息,请发表评论。

最佳答案

您的代码的具体问题:您的 main() 函数缺乏足够的代码来测试反转功能(例如,它不创建任何节点!);您的 create() 例程确实需要 headtail 指针才能正常工作,而不是当前的 head开始;您的反转函数维护头/开始指针,但不处理尾指针;您的 ifelse 子句中有多余的代码,可以将其从条件中取出;您将 rev() 声明为 void * 而不是简单的 void

我修改了下面的代码,解决了上述更改以及一些样式问题:

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

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

// Global pointers to structure
struct node *head = NULL, *tail = NULL;

// Function to add node

void create(int data) {

struct node *temporary = malloc(sizeof(struct node));

temporary->value = data;
temporary->next = NULL;

if (head == NULL) {
head = temporary;
} else {
tail->next = temporary;
}

tail = temporary;
}

// Function to reverse the linked list

void reverse(struct node *previous, struct node *current) {
if (current != NULL) {
reverse(current, current->next);
current->next = previous;
} else {
head = previous;
}

if (previous != NULL) {
tail = previous;
}
}

void display(struct node *temporary) {
while (temporary != NULL) {
printf("%d ", temporary->value);
temporary = temporary->next;
}
printf("\n");
}

// And the related code in main is:

int main() {

/* Code to insert values */
for (int i = 1; i <= 10; i++) {
create(i);
}

display(head);

reverse(NULL, head);

display(head);

create(0);

display(head);

return 0;
}

输出

> ./a.out
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1 0
>

您应该添加一个例程来释放链表中的节点。

关于c - 向函数提供的参数变为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38989135/

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