forked from Hawstein/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.5.cpp
More file actions
111 lines (102 loc) · 1.96 KB
/
3.5.cpp
File metadata and controls
111 lines (102 loc) · 1.96 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
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
class MyQueue{
public:
MyQueue(){
}
~MyQueue(){
}
void push(T val){
move(sout, sin);
sin.push(val);
}
void pop(){
move(sin, sout);
sout.pop();
}
T front(){
move(sin, sout);
return sout.top();
}
T back(){
move(sout, sin);
return sin.top();
}
int size(){
return sin.size()+sout.size();
}
bool empty(){
return sin.empty()&&sout.empty();
}
void move(stack<T> &src, stack<T> &dst){
while(!src.empty()){
dst.push(src.top());
src.pop();
}
}
private:
stack<T> sin, sout;
};
template <typename T>
class MyQueue1{
public:
public:
MyQueue1(){
}
~MyQueue1(){
}
void push(T val){
sin.push(val);
}
void pop(){
move(sin, sout);
sout.pop();
}
T front(){
move(sin, sout);
return sout.top();
}
T back(){
move(sout, sin);
return sin.top();
}
int size(){
return sin.size()+sout.size();
}
bool empty(){
return sin.empty()&&sout.empty();
}
void move(stack<T> &src, stack<T> &dst){
if(dst.empty()){
while(!src.empty()){
dst.push(src.top());
src.pop();
}
}
}
private:
stack<T> sin, sout;
};
int main(){
MyQueue<int> q;
MyQueue1<int> q1;
for(int i=0; i<10; ++i){
q.push(i);
q1.push(i);
}
cout<<q.front()<<" "<<q.back()<<endl;
cout<<q1.front()<<" "<<q1.back()<<endl;
cout<<endl;
q.pop();
q1.pop();
q.push(10);
q1.push(10);
cout<<q.front()<<" "<<q.back()<<endl;
cout<<q1.front()<<" "<<q1.back()<<endl;
cout<<endl;
cout<<q.size()<<" "<<q.empty()<<endl;
cout<<q1.size()<<" "<<q1.empty()<<endl;
return 0;
}