-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseLinkedList.cpp
68 lines (65 loc) · 1.05 KB
/
ReverseLinkedList.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
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int value){
data=value;
next=NULL;
}
};
Node* TakeInput(){
int size;
cin>>size;
Node* head=NULL;
Node* tail=NULL;
while(size--){
int num;
cin>>num;
Node* newNode=new Node(num);
if(head==NULL) head=tail=newNode;
else{
tail->next=newNode;
tail=newNode;
}
}
return head;
}
void IterativeReverseLL(Node* &head){
Node* pre=NULL;
Node* cur=head;
Node* ahead;
while(cur!=NULL){
ahead=cur->next;
cur->next=pre;
pre=cur;
cur=ahead;
}
head=pre;
}
Node* RecursiveReverseLL(Node* head){
if(head==NULL||head->next==NULL) return head;
Node* newNode=RecursiveReverseLL(head->next);
head->next->next=head;
head->next=NULL;
return newNode;
}
void printLL(Node* head){
Node* ptr=head;
while(ptr!=NULL){
cout<<ptr->data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
int main(){
Node* head=TakeInput();
printLL(head);
IterativeReverseLL(head);
printLL(head);
head=RecursiveReverseLL(head);
printLL(head);
return 0;
}
//Time Complexity=O(n)