简体   繁体   English

我正在尝试使用 C 中的递归来反转链表,我对我的递归 function 有一些疑问

[英]I am trying to reverse a linked list using recursion in C, I have some doubts on my recursive function

Below is the program下面是程序

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

struct node
{
    int data;
    struct node *next;
};
struct node *head;
struct node* reverse_ll(struct node* hnode)
{
    if(hnode == 0)
    {
        return 0;
    }
    if(hnode->next == 0)
    {
        head=hnode;
        return hnode;
    }
    struct node* ptr=reverse_ll(hnode->next);
    ptr->next=hnode;
    hnode->next=0;

 //return hnode;
}
void display()
{
    struct node *ptr;
    ptr=head;
    if(ptr==0)
    {
    printf("empty");
    }
    else
    {
        while(ptr!=0)
        {
            printf("%d->",ptr->data);
            ptr=ptr->next;

        }
          printf("null");
    }
}
int main()
{
struct node* h;    
lastinsert(1);
lastinsert(2);
lastinsert(3);
lastinsert(4);
lastinsert(5);
display();
h=reverse_ll(head);
display();
return 0;
}

In function reverse_ll() even if I comment "return hnode" I am getting the right output How is it possible where does ptr receives its address from when I comment "return hnode"?在 function reverse_ll() 中,即使我评论“返回 hnode”,我也得到了正确的 output 当我评论“返回 hnode”时,ptr 如何从哪里接收它的地址?

output: 1->2->3->4->5->null 5->4->3->2->1->null output:1->2->3->4->5->空 5->4->3->2->1->空

reverse_ll() must return a struct node * in the recursive case: reverse_ll()在递归情况下必须返回一个struct node *

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

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

void lastinsert(int data) {
    struct node **c = &head;
    for(; *c; c = &(*c)->next);
    *c = malloc(sizeof(*head));
    if (!(*c)) {
        printf("malloc failed\n");
        return;
    }
    (*c)->data = data;
    (*c)->next = NULL;
}

struct node *reverse_ll(struct node* hnode) {
    if(!hnode)
        return NULL;
    if(!hnode->next) {
        head = hnode;
        return hnode;
    }
    struct node *ptr=reverse_ll(hnode->next);
    ptr->next=hnode;
    hnode->next = NULL;
    return hnode;
}

void display() {
    if(!head) {
        printf("empty");
        return;
    }
    for(struct node *ptr = head; ptr; ptr = ptr->next) {
        printf("%d->",ptr->data);
    }
    printf("null\n");
}

int main() {
    for(int i = 1; i <= 5; i++) {
        lastinsert(i);
    }
    display();
    reverse_ll(head);
    display();
    // It's good practice to implement a function that frees you list
    // which you would call here.
    return 0;
}

and example run:和示例运行:

$ ./a.out
1->2->3->4->5->null
5->4->3->2->1->null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM