LeetCode栈专题-1(go/py3/c++)

每个专题5道,一天一道

232. 用栈实现队列

地址:https://leetcode-cn.com/problems/implement-queue-using-stacks/

解题思路1

两个数据结构的概念:

  • 栈:后进先出
  • 队列:先进先出

题目让我们用两个栈来实现一个队列,就是要让两个栈实现一个先进先出的数据结构。

思路:

「输入栈」会把输入顺序颠倒;如果把「输入栈」的元素逐个弹出放到「输出栈」,再从「输出栈」弹出元素的时候,则可以负负得正,实现了先进先出。

具体做法:

  1. 可以把一个栈当做「输入栈」,把另一个栈当做「输出栈」。
  2. 当 push() 新元素的时候,放到「输入栈」的栈顶,记此顺序为「输入序」。
  3. 当 pop() 元素的时候,是从「输出栈」弹出元素。如果「输出栈」为空,则把「输入栈」的元素逐个 pop() 并且 push() 到「输出栈」中,这一步会把「输入栈」的栈底元素放到了「输出栈」的栈顶。此时负负得正,从「输出栈」的 pop() 元素的顺序与「输入序」相同。
type MyQueue struct {
    stack1,stack2 []int
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    return MyQueue{}
}


/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {
    this.stack1 = append(this.stack1,x)
}

func (this *MyQueue) in2out(){
    for len(this.stack1) > 0 {
        this.stack2 = append(this.stack2,this.stack1[len(this.stack1)-1])
        this.stack1 = this.stack1[:len(this.stack1)-1]
    }
}

/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
    if len(this.stack2) == 0 {
        this.in2out()
    }
    x := this.stack2[len(this.stack2)-1]
    this.stack2 = this.stack2[:len(this.stack2)-1]
    return x
}


/** Get the front element. */
func (this *MyQueue) Peek() int {
    if len(this.stack2) == 0{
        this.in2out()
    }
    return this.stack2[len(this.stack2)-1]
}


/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
    return len(this.stack1)==0 && len(this.stack2)==0
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */
class MyQueue {

private:
    stack<int> stack1,stack2;

    void in2out(){
        while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
        }
    }
    
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(stack2.empty()){
            in2out();
        }
        int x = stack2.top();
        stack2.pop();
        return x;
    }
    
    /** Get the front element. */
    int peek() {
        if(stack2.empty()){
            in2out();
        }
        return stack2.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return stack1.empty() &&  stack2.empty(); 
    }
};

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

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

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack1.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()


    def peek(self) -> int:
        """
        Get the front element.
        """
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return not self.stack1 and not self.stack2



# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

时间复杂度:push() 时间复杂度是 O(1);peek()/pop() 均摊时间复杂度是 O(1),单步操作的最坏时间复杂度是 O(N)。
空间复杂度:空间复杂度是 O(N),因为总的占用了 NN 个元素的空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩波的笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值