-
Notifications
You must be signed in to change notification settings - Fork 0
/
2stack_array.cpp
144 lines (128 loc) · 3.13 KB
/
2stack_array.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// 2. Implement Stack ADT using array in CPP.
// Theory:
// This code implements a stack using a class Stack with
// functionalities like initialization, checking if the stack is empty
// or full, pushing elements onto the stack, popping elements from
// the stack, and peeking at the top element. The main function
// provides menu-driven interface for users to interact with the stack.
#include <iostream>
using namespace std;
class Stack
{
private:
int capacity;
int *arr;
int top;
public:
void init(int cap)
{
capacity = cap;
arr = new int[capacity];
top = -1;
}
bool isEmpty()
{
return top == -1;
}
bool isFull()
{
return top == capacity - 1;
}
void push(int element)
{
if (!isFull())
{
arr[++top] = element;
cout << element << " pushed in stack." << endl;
}
else
{
cout << "stack overflow" << endl;
}
}
int pop()
{
if (!isEmpty())
{
int element = arr[top--];
cout << element << " popped from stack" << endl;
return element;
}
else
{
cout << "stack underflow" << endl;
return -1;
}
}
int peek()
{
if (!isEmpty())
{
return arr[top];
}
else
{
cout << "stack is empty" << endl;
return -1;
}
}
};
int main()
{
Stack stack;
int capacity;
cout << "enter capacity of stack: ";
cin >> capacity;
stack.init(capacity);
int num_elements;
cout << "how many elements do you want to push in stack? ";
cin >> num_elements;
int element;
for (int i = 0; i < num_elements; ++i)
{
cout << "enter element " << i + 1 << ": ";
cin >> element;
stack.push(element);
}
int choice;
do
{
cout << "\n1. push\n";
cout << "2. pop\n";
cout << "3. peek\n";
cout << "4. exit\n";
cout << "enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "enter element to push in stack: ";
cin >> element;
stack.push(element);
break;
case 2:
stack.pop();
break;
case 3:
element = stack.peek();
if (element != -1)
{
cout << "top element of stack: " << element << endl;
}
break;
case 4:
cout << "exited!\n";
break;
default:
cout << "invalid choice" << endl;
}
}
while (choice != 4);
return 0;
}
// Conclusion:
// The code offers a basic implementation of a stack data structure
// with essential operations like push, pop, and peek. It provides a
// user-friendly menu interface for interacting with the stack,
// allowing users to push elements onto the stack, pop elements from
// it, and view the top element.