assignment_18.cpp
Problem Statement
assignment_18.cpp
WAP to reverse the order of the elements in the stack using additional stack.
Source Code
cpp
#include <iostream>
using namespace std;
class Stack {
private:
int *arr;
int top;
int capacity;
public:
Stack(int size) {
capacity = size;
arr = new int[capacity];
top = -1;
}
Stack(const Stack&) = delete;
Stack& operator=(const Stack&) = delete;
bool isFull() const { return (top == capacity - 1); }
bool isEmpty() const { return (top == -1); }
void push(int val) {
if (isFull()) { cout << "Stack Overflow!\n"; return; }
arr[++top] = val;
}
int pop() {
if (isEmpty()) { cout << "Stack Underflow!\n"; return -1; }
return arr[top--];
}
void display() const {
if (isEmpty()) { cout << "Stack is empty!\n"; return; }
for (int i = top; i >= 0; i--) cout << arr[i] << " ";
cout << endl;
}
void reverseUsingAdditionalStacks() {
if (isEmpty()) { cout << "Stack is empty! Nothing to reverse.\n"; return; }
Stack s1(capacity);
Stack s2(capacity);
while (!isEmpty()) s1.push(pop());
while (!s1.isEmpty()) s2.push(s1.pop());
while (!s2.isEmpty()) push(s2.pop());
}
~Stack() { delete[] arr; }
};
int main() {
int size, choice, val;
cout << "Enter the capacity of the stack: ";
cin >> size;
if (size <= 0) { cout << "Invalid stack size!\n"; return 0; }
Stack s(size);
while (true) {
cout << "1.push 2.pop 3.reverse 0.display -1.Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value: ";
cin >> val;
s.push(val);
break;
case 2: {
int v = s.pop();
if (v != -1) cout << "Popped element: " << v << endl;
break;
}
case 3:
s.reverseUsingAdditionalStacks();
cout << "Stack reversed.\n"; // Added feedback
break;
case 0:
s.display();
break;
case -1:
cout << "Exiting...\n";
return 0;
default:
cout << "Wrong choice.\n";
}
}
}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
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