-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_based_2stacks.cpp
More file actions
97 lines (82 loc) · 1.6 KB
/
array_based_2stacks.cpp
File metadata and controls
97 lines (82 loc) · 1.6 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
#include <bits/stdc++.h>
using namespace std;
class Stack
{
private:
int size{};
int top1{}, top2{};
int *array{};
public:
Stack(int size)
{
this->size = size;
top1 = -1;
top2 = size;
array = new int[size];
}
~Stack()
{
delete[] array;
}
bool isFull()
{
return top1 >= top2 - 1;
}
bool isEmpty(int id)
{
if (id == 1)
return top1 == -1;
return top2 == size;
}
void push(int id, int value)
{
assert(!isFull());
if (id == 1)
array[++top1] = value;
else
array[--top2] = value;
}
int peek(int id)
{
assert(!isEmpty(id));
if (id == 1)
return array[top1];
return array[top2];
}
int pop(int id)
{
assert(!isEmpty(id));
if (id == 1)
return array[top1--];
else
return array[top2++];
}
void display()
{
for (int i = top1; i >= 0; i--)
cout << array[i] << " ";
cout << "\n";
for (int i = top2; i < size; i++)
cout << array[i] << " ";
cout << "\n";
}
};
int main()
{
Stack stack(10);
stack.push(2, 5);
stack.push(2, 6);
cout << stack.pop(2) << endl;
stack.push(2, 7);
stack.push(2, 9);
stack.push(1, 4);
cout << stack.peek(1) << endl;
cout << stack.peek(2) << endl;
stack.push(1, 6);
stack.push(1, 8);
stack.push(2, 3);
stack.display();
// must see it, otherwise RTE
cout << "\n\nNO RTE\n";
return 0;
}