-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_based_stack.cpp
More file actions
115 lines (94 loc) · 1.81 KB
/
array_based_stack.cpp
File metadata and controls
115 lines (94 loc) · 1.81 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
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
#include <bits/stdc++.h>
using namespace std;
class Stack
{
private:
int size{};
int top{};
int *array{};
public:
Stack(int size)
{
this->size = size;
top = -1;
array = new int[size];
}
bool isFull()
{
return top == size - 1;
}
bool isEmpty()
{
return top == -1;
}
void push(int value)
{
assert(!isFull());
array[++top] = value;
}
int peek()
{
assert(!isEmpty());
return array[top];
}
int pop()
{
assert(!isEmpty());
return array[top--];
}
void display()
{
for (int i = top; i >= 0; i--)
cout << array[i] << " ";
cout << "\n";
}
void insert_at_bottom_iterative(int value)
{
assert(!isFull());
top++;
for (int i = top; i > 0; i--)
array[i] = array[i - 1];
array[0] = value;
}
void insert_at_bottom(int value)
{
if (isEmpty())
{
push(value);
return;
}
int cur = pop();
insert_at_bottom(value);
push(cur);
}
void reverse()
{
if (isEmpty())
return;
int cur = pop();
reverse();
insert_at_bottom(cur);
}
};
int main()
{
Stack stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
// cout << stack.isFull() << endl;
// cout << stack.peek() << endl;
// stack.display();
// stack.pop();
// cout << stack.isFull() << endl;
// cout << stack.peek() << endl;
stack.display();
stack.insert_at_bottom_iterative(40);
stack.insert_at_bottom(50);
stack.display();
stack.reverse();
stack.display();
// must see it, otherwise RTE
cout << "\n\nNO RTE\n";
return 0;
}