利用栈实现队列

C++库中的stack

stack模板类的定义在stack头文件中
stack的基本操作有:
1. 入栈:s.push();
2. 出栈:s.pop(),注意它不返回元素的值;
3. 访问栈顶元素:s.top();
4. 栈中元素的个数:s.size();
5. 判断栈是否为空:s.empty();

我们利用栈的这些特点来实现我们的队列

做法如下:
1. 用一个size来记录队列的容量,实现队列需要两个栈s1,s2;
2. 入队时,我们将元素压入s1;
3. 出队时,如果s2有元素,就弹出s2的栈顶元素;如果没有,则将s1中的所有元素弹出并压入s2中,再弹出s2的栈顶元素;
4. 查看队头元素操作同上,只是不需要弹出s2的栈顶元素;
代码如下:

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
#include <iostream>
#include <stack>
using namespace std;

class Queue {
public:
    int size = 0;
    stack<int> s1;
    stack<int> s2;

    // Push element x to the back of queue.
    void push(int x) {
        s1.push(x);
        size++;
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if (!s2.empty()) {
            s2.pop();
        }else{
            while (!s1.empty()) {
                int t = s1.top();
                s1.pop();
                s2.push(t);
            }
            s2.pop();
        }
        size--;
    }

    // Get the front element.
    int peek(void) {
        if (!s2.empty()) {
            return s2.top();
        }else{
            while (!s1.empty()) {
                int t = s1.top();
                s1.pop();
                s2.push(t);
            }
            return s2.top();
        }
    }

    // Return whether the queue is empty.
    bool empty(void) {
        if (size==0) {
            return true;
        }else{
            return false;
        }
    }
};

Comments