-
Notifications
You must be signed in to change notification settings - Fork 4
/
1-2.两个栈实现队列.cpp
74 lines (63 loc) · 1.16 KB
/
1-2.两个栈实现队列.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
#include <iostream>
#include <stack>
#define ERROR -10000
using namespace std;
class myQueue {
public:
void add( int x );
int poll();
int peek();
private:
stack<int> s1;
stack<int> s2;
};
void myQueue::add( int x ) {
s1.push( x );
}
int myQueue::poll() {
int res;
res = peek();
if( res != ERROR ) {
s2.pop();
}
return res;
}
int myQueue::peek() {
int res;
if( !s2.empty() ) {
res = s2.top();
}
else {
if( s1.empty() ) {
printf( "the queue is empty!\n" );
return ERROR;
}
else {
while( !s1.empty() ) {
int cur = s1.top();
s1.pop();
s2.push( cur );
}
res = s2.top();
}
}
return res;
}
int main() {
myQueue q;
q.add( 1 );
q.add( 2 );
q.add( 3 );
printf( "%d\n", q.peek() );
q.poll();
printf( "%d\n", q.peek() );
q.poll();
q.add( 5 );
q.add( 6 );
printf( "%d\n", q.peek() );
q.poll();
printf( "%d\n", q.peek() );
q.poll();
printf( "%d\n", q.peek() );
return 0;
}