力扣232_用栈实现队列

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

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

算法思想:
一个栈作为输入栈,用于push数据,一个栈作为输出栈,用于pop和peek数据,当有数据要入队时,全部push到输入栈,当队列有数据要出队时,先看输出栈是否为空,若不为空则将栈顶元素出栈,若为空则将输入栈内的所有数据出栈并压入输出栈中

代码如下

class MyQueue {

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

复杂度分析:
时间复杂度:push为O(1),因为只有输出栈为空才会进行数据移动,所有pop和peek均摊下来为O(1)
空间复杂度:O(n)

你可能感兴趣的:(刷题日记,算法,栈,数据结构,java)