简体   繁体   English

使用递归在C中反向链表

[英]reverse linked list in C using recursion

I have written following code in C. I am pretty new to C. The insert and Print functions seem to work fine but I get a prompt that says program stopped working when I call Reverse function. 我在C中编写了以下代码。我是C的新手。插入和打印功能似乎工作正常,但我得到一个提示,说当我调用Reverse函数时程序停止工作。 Where dis I go wrong ? 我哪里出错了?

//WAP to reverse a Linked List using recursion

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

struct Node{
    int data;
    struct Node* next;
};
struct Node* head;  //global variable

struct Node* Reverse(struct Node* p){
    if(p->next == NULL){  //since for last node link part is null
        head = p;
        printf("break condition");
        return head;
    }
    printf("calling reverse");
    Reverse(p->next);
    struct Node* q = p->next;
    q->next = p;
    p->next = NULL;
}

void Insert(int x){
    struct Node* temp= (struct Node*)malloc(sizeof(struct Node));
    temp->data = x;
    //temp->next = NULL; //redundant
    //if(head!= NULL){
    temp->next = head;  //temp.next will point to null when head is null nd otherwise what head was pointing to
    //}
    head = temp;
}

void Print(){
    struct Node* temp1 = head;  //we dont want tomodify head so store it in atemp. bariable and then traverse
    while(temp1 != NULL){
        printf(" %d", temp1->data);
        temp1= temp1->next;
    }
    printf("\n");
}

int main(){
    struct Node* head = NULL;
    Insert(2);
    Insert(4);
    Insert(5);
    Insert(1);
    Print();
    head = Reverse(head);
    //  Print();
}

There are two issues with the program above: 上述程序存在两个问题:

1) You have two head variables. 1)你有两个head变量。 One is a global variable, and the other is a variable local to the main function. 一个是全局变量,另一个是main函数的局部变量。 That local variable is the one that is passed to Reverse() . 该局部变量是传递给Reverse()变量。 Since the first thing that function does is dereferencing it, the program crashes. 由于函数的第一件事是解除引用它,程序崩溃了。 Removing the local head variable in the main() function should address it. 删除main()函数中的本地head变量应解决它。

2) The Reverse() function correctly returns head when it reaches the exit condition, but what happens the rest of the time? 2) Reverse()函数在达到退出条件时正确返回head ,但其余时间会发生什么? It's missing a return in the non-exit condition case. 它在非退出条件情况下错过了返回。 Here's a diff that would address the issue: 这是一个解决问题的差异:

    printf("calling reverse");
-   Reverse(p->next);
+   struct Node* ret;
+   ret = Reverse(p->next);
    struct Node* q = p->next;
    q->next = p;
    p->next = NULL;
+   return ret;

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

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