forked from Hawstein/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3.3.cpp
140 lines (134 loc) · 2.59 KB
/
3.3.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
#include <iostream>
using namespace std;
const int STACK_SIZE = 100;
const int STACK_NUM = 10;
class stack{
private:
int *buf;
int cur;
int capacity;
public:
stack(int capa = STACK_SIZE){
buf = new int[capa];
cur = -1;
capacity = capa;
}
~stack(){
delete[] buf;
}
void push(int val){
buf[++cur] = val;
}
void pop(){
--cur;
}
int top(){
return buf[cur];
}
bool empty(){
return cur==-1;
}
bool full(){
return cur==capacity-1;
}
};
class SetOfStacks{//without popAt()
private:
stack *st;
int cur;
int capacity;
public:
SetOfStacks(int capa=STACK_NUM){
st = new stack[capa];
cur = 0;
capacity = capa;
}
~SetOfStacks(){
delete[] st;
}
void push(int val){
if(st[cur].full()) ++cur;
st[cur].push(val);
}
void pop(){
if(st[cur].empty()) --cur;
st[cur].pop();
}
int top(){
if(st[cur].empty()) --cur;
return st[cur].top();
}
bool empty(){
if(cur==0) return st[0].empty();
else return false;
}
bool full(){
if(cur==capacity-1) return st[cur].full();
else return false;
}
};
class SetOfStacks1{
private:
stack *st;
int cur;
int capacity;
public:
SetOfStacks1(int capa=STACK_NUM){
st = new stack[capa];
cur = 0;
capacity = capa;
}
~SetOfStacks1(){
delete[] st;
}
void push(int val){
if(st[cur].full()) ++cur;
st[cur].push(val);
}
void pop(){
while(st[cur].empty()) --cur;
st[cur].pop();
}
void popAt(int idx){
while(st[idx].empty()) --idx;
st[idx].pop();
}
int top(){
while(st[cur].empty()) --cur;
return st[cur].top();
}
bool empty(){
while(cur!=-1 && st[cur].empty()) --cur;
if(cur==-1) return true;
else return false;
}
bool full(){
if(cur==capacity-1) return st[cur].full();
else return false;
}
};
int main(){
// SetOfStacks ss;
// for(int i=0; i<STACK_SIZE+1; ++i){
// ss.push(i);
// }
// while(!ss.empty()){
// cout<<ss.top()<<endl;
// ss.pop();
// }
SetOfStacks1 ss1;
for(int i=0; i<3*STACK_SIZE+1; ++i){
ss1.push(i);
}
for(int i=0; i<STACK_SIZE; ++i){
ss1.popAt(0);
//ss1.popAt(1);
ss1.popAt(2);
}
ss1.popAt(3);
while(!ss1.empty()){
cout<<ss1.top()<<endl;
ss1.pop();
}
return 0;
}