-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse-the-list-using-stack.cpp
97 lines (74 loc) · 1.7 KB
/
reverse-the-list-using-stack.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
Algorithm:
(i) Traverse the list and push all of its nodes onto a stack.
(ii) Traverse the list from the head node again and pop a value
from the stack top and connect them in reverse order.
TIME COMPLEXITY: O(n), as we are traversing over the linked list of size N using a while loop.
SPACE COMPLEXITY: o(n), as we are using stack of size N in worst case which is extra space.
*/
#include <iostream>
#include <stack>
using namespace std;
class Node {
public:
int data;
Node *next;
};
Node *head;
void Print(Node* n);
void RevList();
int main() {
head = NULL;
Node *first = new Node;
Node *second = new Node;
Node *third = new Node;
Node *fourth = new Node;
Node *fifth = new Node;
Node *sixth = new Node;
Node *seventh = new Node;
head = first;
first->data = 10;
first->next = second;
second->data = 20;
second->next = third;
third->data = 30;
third->next = fourth;
fourth->data = 40;
fourth->next = fifth;
fifth->data = 50;
fifth->next = sixth;
sixth->data = 60;
sixth->next = seventh;
seventh->data = 70;
seventh->next = NULL;
Print(head);
RevList();
cout<<endl;
Print(head);
return 0;
}
void Print(Node* n){
if(n==NULL){
return;
}
cout<<n->data<<" ";
Print(n->next);
}
void RevList() {
if(head == NULL) return;
stack<Node *> st;
Node * temp = head;
while(temp!= NULL){
st.push(temp);
temp = temp->next;
}
temp = st.top();
head = temp;
st.pop();
while(!st.empty()) {
temp->next = st.top();
temp = temp->next;
st.pop();
}
temp->next = NULL;
}