-
Notifications
You must be signed in to change notification settings - Fork 2
/
Two stacks in one array.cpp
134 lines (103 loc) · 2.55 KB
/
Two stacks in one 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
//Implementation of two stacks in one array
//For space efficiency, the stacks stacks start piling elements form
//opposite sides of the array
#include <iostream>
#include <cstdlib>
using namespace std;
//Binary stack/ 2stacks in one array
template <typename T>
class binStack{
private:
//length of array, position of top for stack 1 and 2
int len, peek1, peek2;
T* data;
public:
binStack(int sz){ //size of the whole array
data = new T[sz];
len = sz;
peek1= -1;
peek2= sz;
}
//All both stacks have their own methods same name but numbered 1 and 2
int size1(){
return peek1+1;
}
int size2(){
return len-peek2;
}
bool full(){
return peek1 == peek2-1;
}
bool empty1(){
return peek1 == -1;
}
bool empty2(){
return peek2 == len;
}
T& top1(void){
return data[peek1];
}
T& top2(void){
return data[peek2];
}
void push1(T obj){
//if there is no space between the two stacks
if(full()){
std::cerr<<"Stack Overflow Error!"<<std::endl;
exit(1);
}
peek1++;
data[peek1] = obj;
}
void push2(T obj){
//if there is no space between the two stacks
if(full()){
std::cerr<<"Stack Overflow Error!"<<std::endl;
exit(1);
}
peek2--;
data[peek2] = obj;
}
T pop1(void){
if(empty1()){ //if first stack has no elements
std::cerr<<"Stack Underflow Error!"<<std::endl;
exit(1);
}
peek1--;
return data[peek1+1];
}
T pop2(void){
if(empty2()){ //if second stack has no elements
std::cerr<<"Stack Underflow Error!"<<std::endl;
exit(1);
}
peek2++;
return data[peek1-1];
}
};
int main(void)
{
binStack<int> stacks(6);
stacks.push1(1);
stacks.push1(2);
stacks.push1(3);
// stacks.push1(7);
stacks.push2(9);
stacks.push2(8);
stacks.push2(7);
cout<<"stack 1:"<<endl;
cout<< stacks.top1() <<endl;
stacks.pop1();
cout<< stacks.top1() <<endl;
stacks.pop1();
cout<< stacks.top1() <<endl;
stacks.pop1();
cout<<"\nstack 2:"<<endl;
cout<< stacks.top2() <<endl;
stacks.pop2();
cout<< stacks.top2() <<endl;
stacks.pop2();
cout<< stacks.top2() <<endl;
stacks.pop2();
return 0;
}