-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_stack.cpp
More file actions
85 lines (75 loc) · 1.41 KB
/
reverse_stack.cpp
File metadata and controls
85 lines (75 loc) · 1.41 KB
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
// reverse stack
// link - https://www.geeksforgeeks.org/problems/reverse-a-stack/1
/*
You are given a stack St. You have to reverse the stack using recursion or iteration.
*/
#include <iostream>
#include <stack>
using namespace std;
// Recursive approach
// Time: O(N^2), Space: O(N) (due to recursion stack)
void insertAtBottom(stack<int> &s, int x)
{
if (s.empty())
{
s.push(x);
return;
}
int top = s.top();
s.pop();
insertAtBottom(s, x);
s.push(top);
}
void ReverseRecursive(stack<int> &s)
{
if (s.empty())
return;
int top = s.top();
s.pop();
ReverseRecursive(s);
insertAtBottom(s, top);
}
// Iterative approach
// Time: O(N), Space: O(N)
void Reverse(stack<int> &St)
{
stack<int> temp;
while (!St.empty())
{
temp.push(St.top());
St.pop();
}
St = temp;
return;
}
// Utility function to print stack from top to bottom
void printStack(stack<int> s)
{
cout << "Stack (top to bottom): ";
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
}
int main()
{
stack<int> s;
s.push(3);
s.push(2);
s.push(1);
s.push(7);
s.push(6);
cout << "Original stack: ";
printStack(s);
// Iterative approach
Reverse(s);
cout << "Reversed stack (iterative): ";
printStack(s);
// Reverse again using recursive approach to restore original order
ReverseRecursive(s);
cout << "Reversed stack (recursive): ";
printStack(s);
return 0;
}