码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode232. 用栈实现队列

时间:2020-05-24 16:51:25      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:java   hat   使用   int   from   elf   tac   returns   rom   

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

 push操作搞一个辅助栈就好了

 

python

class MyQueue:

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

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

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        return self.stack.pop();

    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.stack[-1]


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


# 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()

 Java

class MyQueue {
    Stack<Integer>pushStack=new Stack<>();
    Stack<Integer>popStack=new Stack<>();

    /** Initialize your data structure here. */
    public MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!popStack.isEmpty()){
            pushStack.push(popStack.pop());
        }
        pushStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(!pushStack.isEmpty()){
            popStack.push(pushStack.pop());
        }
        return popStack.pop();
    }
    
    /** Get the front element. */
    public int peek() {
         while(!pushStack.isEmpty()){
            popStack.push(pushStack.pop());
        }
        return popStack.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return pushStack.isEmpty()&&popStack.isEmpty();
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */

 

leetcode232. 用栈实现队列

标签:java   hat   使用   int   from   elf   tac   returns   rom   

原文地址:https://www.cnblogs.com/xxxsans/p/12951180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!