ronith
7/9/2018 - 4:48 AM

Print reverse of a Linked List without actually reversing

Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.

// https://www.geeksforgeeks.org/print-reverse-of-a-linked-list-without-actually-reversing/
#include <iostream>
#include <list>
using namespace std;

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

void print (node* head) {
    while (head) {
        cout<< head->data << "->";
        head =head->next;
    }
}

void printreverse (node* head) {
    if (head == NULL)
        return;
    printreverse(head->next);
    cout<< head->data << "->";
}

node* insert(node* head, int n) {
    if (head == NULL) {
        node* list = (node*)malloc(sizeof(node));
        list->data = n;
        list->next = NULL;
        head = list;
        return head;
    }
    node* list = (node*)malloc(sizeof(node));
    list->data = n;
    list->next = NULL;
    node* end = head;
    while (end->next)
        end = end->next;
    end->next = list;
    return head;
}

int main() {
    int n;
    node* head = NULL;
    while (true) {
        cout<< "enter the number: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head = insert(head, n);
    }
    print(head);
    cout<< "\n";
    printreverse(head);
}