leetcode-232-用栈实现队列

题目描述:

 

 

方法一:双栈

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import deque
        self.stack = deque()

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

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

    def peek(self) -> int:
        """
        Get the front element.
        """
        if self.stack: 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 CQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    int size;

    public CQueue() {
        stack1 = new Stack<> ();
        stack2 = new Stack<> ();
        size = 0;
    }
    
    public void appendTail(int value) {
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        stack1.push(value);
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        size++;
    }
    
    public int deleteHead() {
        if(size == 0){
            return -1;
        }
        size--;
        return stack1.pop();
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

 

posted @ 2019-10-05 18:47  oldby  阅读(176)  评论(0编辑  收藏  举报