队列和栈的相互表示

本文探讨如何使用栈来表示队列,包括两种不同的实现方法,并介绍了如何用队列来表示栈,详细阐述了各自的push、pop、front、empty等操作的处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用栈表示队列

方法1:
1.用两个栈tmp和S,tmp当做中介。
2.每次有push操作时,先将s中的元素全部倒入tmp中(s若为空则无操作),此时再进行push操作压入新元素。
3.操作完成后再将tmp中所有元素倒入s中,从s中弹出的元素即为队列元素的弹出顺序。
4.pop操作则为s.pop(),empty则为s.empty()。top操作也是取s的top。
方法2(方法1的改进):
1.在方法1pop操作时先判断s是否为空,如果不为空直接进行s.pop(),如果为空,则此时直接将tmp中的元素倒入s中,对s进行pop;
2.取top操作和pop操作类似,判断栈空要看两个栈是否都为空,size操作也一样。
方法一代码

class Queue {
public:
    stack<int> tmp, s;
    // Push element x to the back of queue.
    void push(int x) {

        while (!s.empty()){
            tmp.push(s.top());
            s.pop();
        }
        tmp.push(x);
        while (!tmp.empty()){
            s.push(tmp.top());
            tmp.pop();
        }
    }

    // Removes the element from in front of queue.
    void pop(void) {
        s.pop();
    }

    // Get the front element.
    int peek(void) {
        return s.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return s.empty();
    }
};

用队列表示栈

方法一
1.建立两个队列q和tmp,tmp为中介。
2.push:将q中的元素按出队列顺序倒入tmp中,然后元素压入q中,再将tmp中元素按顺序倒回q中。
3.pop:q.pop()。front:q.front();。empty:q.empty();
方法一代码

class Stack {
public:
    queue<int> q, tmp;
    // Push element x onto stack.
    void push(int x) {

        while (!q.empty()){
            tmp.push(q.front());
            q.pop();
        }
        q.push(x);

        while (!tmp.empty()){
            q.push(tmp.front());
            tmp.pop();
        }
    }

    // Removes the element on top of the stack.
    void pop() {
        q.pop();
    }

    // Get the top element.
    int top() {
        return q.front();
    }

    // Return whether the stack is empty.
    bool empty() {
        return  q.empty();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值