栈和队列OJ题

这篇博客探讨了如何仅使用两个队列来实现一个后入先出(LIFO)的栈,以及如何用两个栈实现先进先出(FIFO)的队列。在栈的实现中,通过主队列和辅助队列的巧妙转换保证了栈的操作;而在队列的实现中,利用两个栈,确保在执行各种操作时始终有一个栈为空,从而达到队列的效果。这种方法展示了数据结构的灵活性和创造性。
摘要由CSDN通过智能技术生成

用队列实现栈

**题目描述:**请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
思路:我们可以使用两个队列,一个队列当作存储栈的主队列,另外一个作为辅助队列,用来帮助主队列实现栈的功能。

class MyStack {
public:
    queue<int> queue1;
    queue<int> queue2;

    /** Initialize your data structure here. */
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
    //先将要插入元素插进辅助队列中
        queue2.push(x);
        //当主队列不为空时,将主队列中的所有元素插入辅助队列中,这样可以保证主队列中的之前的元素都在要插入元素的后面。即使主队列为空时,直接交换两个队列即可。
        while (!queue1.empty()) {
            queue2.push(queue1.front());
            queue1.pop();
        }
        swap(queue1, queue2);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    //弹出栈中顶的元素(或者新插入的元素)——》新插入的元素在主队列的头部。即返回主队了的头部的数据即可。
    int pop() {
        int r = queue1.front();
        queue1.pop();
        return r;
    }
    
    /** Get the top element. */
    int top() {
        int r = queue1.front();
        return r;
    }
    
    /** Returns whether the stack is empty. */
    //直接判断主队列是否为空即可。
    bool empty() {
        return queue1.empty();
    }
};

用栈实现队列

**题目描述:**请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

解题思路:

不管在执行什么操作时,一定要保证其中的一个栈为空,比如(插入元素时,必须保证出栈的这个栈为空)

class MyQueue {
public:
    stack<int>in_stack;//主栈
    stack<int>out_stack;//辅助栈
    MyQueue() {
        //初始化
        while(!in_stack.empty())
        {
            in_stack.pop();
        }
         while(!out_stack.empty())
        {
            out_stack.pop();
        }

    }
    
    void push(int x) {
       while(!out_stack.empty())
       {
           in_stack.push(out_stack.top());
           out_stack.pop();
       }
       in_stack.push(x);

    }
    
    int pop() {
        while(!in_stack.empty())
        {
            out_stack.push(in_stack.top());
            in_stack.pop();
        }
        int x=out_stack.top();
        out_stack.pop();
        return x;
    }
    
    int peek() {
        while(!in_stack.empty())
        {
            out_stack.push(in_stack.top());
            in_stack.pop();
        }
        return out_stack.top();

    }
    
    bool empty() {
        return in_stack.empty()&&out_stack.empty();

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值