LeetCode探索之旅(63)-225用队列表示栈

今天继续刷LeetCode,第225题,用队列的操作来实现栈的功能。

分析:
因为栈是先进后出,那么对于一个先进先出的队列来说,可能无法满足需求,那么就可以通过两个队列来实现一个栈的功能。出栈的时候,选择先出队列,再入队列,将队列最后一个元素输出,就是栈的输出了。

问题:
1、队列用列表的方式表示的时候,可以有两种插入方式,一个是append加入到尾部,一个是insert插入到头部。
2、注意Python中self的应用。

附上C++代码:

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
             
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        top_value=x;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        queue<int> temp;
        while(q.size()!=1)
        {
            temp.push(q.front());
            top_value=q.front();
            q.pop();
        }
        int value=q.front();
        q.pop();
        q=temp;
        return value;
    }
    
    /** Get the top element. */
    int top() {
        return top_value;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
private:
    queue<int> q;
    int top_value;
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

附上Python代码:

class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.inQueue=[]
        self.outQueue=[]

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.inQueue.insert(0,x)

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        for _ in range(len(self.inQueue)-1):
            self.outQueue.insert(0,self.inQueue.pop())
        res=self.inQueue.pop()
        self.inQueue=self.outQueue
        self.outQueue=[]
        return res
 
    def top(self) -> int:
        """
        Get the top element.
        """
        for _ in range(len(self.inQueue)-1):
            self.outQueue.insert(0,self.inQueue.pop())
        res=self.inQueue.pop()
        self.outQueue.insert(0,res)
        self.inQueue=self.outQueue
        self.outQueue=[]
        return res

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        if len(self.inQueue)==0:
            return True
        else:
            return False


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值