-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse LL using Recursion.cpp
53 lines (53 loc) · 1023 Bytes
/
Reverse LL using Recursion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//Reverse LL using Recursion
#include<bits/stdc++.h>
using namespace std ;
class Node
{
public:
int data ;
Node* next ;
Node(int data)
{
this->data = data ;
this->next = NULL ;
}
};
Node* rev(Node* head)
{
if(head == NULL)
return head ;
Node *temp = rev(head->next) ;
Node *ptr = temp ;
head->next = NULL;
if(temp == NULL)
return head ;
while(temp->next != NULL)
{
temp = temp->next ;
}
temp->next = head ;
head = ptr ;
return head ;
}
int main()
{
Node *x = new Node(1);
Node *y = new Node(2);
Node *z = new Node(3);
Node *a = new Node(4);
Node *b = new Node(5);
Node *c = new Node(6);
x->next = y ;
y->next = z ;
z->next = a ;
a->next = b ;
b->next = c ;
Node *head = rev(x) ;
Node *temp = head ;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next ;
}
return 0;
}