利用队列实现栈

C++库中的queue:

queue 模板类的定义在queue头文件中
queue 的基本操作有:
1. 入队:q.push(x);
2. 出队:q.pop(),注意它不返回元素的值;
3. 访问队首元素: q.front();
4. 访问队尾元素: q.back();
5. 队列的元素个数: q.size();
6. 判断队列是否为空: q.empty();

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

做法如下:
1. 用一个size来记录栈的容量,实现栈需要利用两个队列q1、q2;
2. 压栈时,将元素插入到非空队列里;
3. 弹栈时,先取得非空队列q1,弹出元素插入到空队列q2中,直到只剩下最后一个元素,弹栈就是弹出这个元素,且不插入到q2中;
4. 查看栈顶元素,操作同上,只是最后那个元素最终要插入到q2中;
代码如下:

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
#include <iostream>
#include <queue>
using namespace std;
class Stack {
    int size=0;
    queue<int> q1;
    queue<int> q2;
public:
    // Push element x onto stack.
    void push(int x) {
        if (empty()||!q1.empty()) {
            q1.push(x);
        }else{
            q2.push(x);
        }
        size++;
    }

    // Removes the element on top of the stack.
    void pop() {
        if (!q1.empty()) {
            while (q1.size()>1) {
                int a = q1.front();
                q1.pop();
                q2.push(a);
            }
            q1.pop();
        }else{
            while (q2.size()>1) {
                int a = q2.front();
                q2.pop();
                q1.push(a);
            }
            q2.pop();
        }
        size--;
    }

    // Get the top element.
    int top() {
        if (!q1.empty()) {
            return q1.back();
        }else{
            return q2.back();
        }
    }

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

Comments