-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_LL.cpp
72 lines (61 loc) · 1.31 KB
/
reverse_LL.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data = 0){
this->data = data;
this->next = NULL;
}
};
void insertAtHead(Node* &head, int data){
// 1] Create a temp node
Node* temp = new Node(data);
// 2] attach temp n head node by
temp->next = head;
// 3] bring head at starting
head = temp;
}
void print(Node* &head){
Node* temp = head;
while(temp){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
// using iteratiom
Node* reverseLL(Node* &head){
if(head == NULL){
cout<<"Empty LL"<<endl;
return;
}
Node* p = NULL, *q = head, *r = NULL;
while(q){
p = q->next;
q->next = r;
r = q;
q = p;
}
return r;
}
// using recursion
Node* reverseLL(Node* prev, Node* curr){
if(curr == NULL)
return prev;
Node* next = curr->next;
curr->next = prev;
return reverseLL(curr,next);
}
int main(){
Node* head = new Node(90);
insertAtHead(head,80);
insertAtHead(head,70);
insertAtHead(head,60);
insertAtHead(head,50);
Node* curr = head, *prev = NULL;
head = reverseLL(prev,curr);
print(head);
return 0;
}