sadkm
sadkm

Reputation: 1

How to display reverse of a list using recursion?

This code is implementation of singly linked list using c. I first element while trying to print the reverse of the list using recursive function. What is the mistake I made here? I just want to print the reverse of the list, I dont want the list to be reversed permanently, but function to reverse this permanently is also welcomed as I want to learn that too.

P.S: I should submit this code to my teacher tomorrow so please don't give corrected code in different format.

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

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

typedef struct list {
    Node *head;
} List;

List *emptylist() {
    List *list = malloc(sizeof(List));
    list->head = NULL;
    return list;
}

Node *createnode(int data) {
    Node *newNode = malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

//Display reverse using recursion
void reversedis(List list) {
    if (list.head==NULL || list.head->next==NULL) return;
    else {
        list.head=list.head->next;
        reversedis(list);
        printf("%d,",list.head->data);
    }
}

Upvotes: 0

Views: 86

Answers (2)

eniacz
eniacz

Reputation: 127

First make sure your reversedis() does't modify the list structure

   void reversedis(Node *node){
       if (node==NULL) return;
       else{
           reversedis(node->next);
           printf("%d,",node->data);
       }
   }

then in main()

       reversedis(l->head);

Upvotes: 2

Barmar
Barmar

Reputation: 780879

The problem is that you're changing list.head before you print list.head->data, so you lose the current element. I'm not sure why this is causing a segmentation error, though, you should just miss the first element.

Make a temporary copy of list and modify that.

void reversedis (List list) {
    if (list.head == NULL) {
        return;
    }
    List temp = list;
    temp.head = temp.next;
    reversedis(temp);
    printf("%d,", list.head->data);
}

Upvotes: 1

Related Questions