算法修炼Day10|232.用栈实现队列 ● 225. 用队列实现栈

93 阅读1分钟

LeetCode:232. 用栈实现队列 - 力扣(LeetCode)

1.思路

队列双端操作数据,栈单边操作数据,所以声明的两个栈分别用作入栈和出栈,在pop()和peek()时,需注意,出栈中为空才能进行出栈而后入栈!!

2.代码实现
// 函数复用
class MyQueue {

    Stack<Integer> stack1;
    Stack<Integer> stack2;

    public MyQueue() {
        stack1 = new Stack<>(); // 负责进栈
        stack2 = new Stack<>(); // 负责出栈
    }
    
    public void push(int x) {
        stack1.push(x);
    }
    
    public int pop() {
        dumpstack1();
        return stack2.pop();
    }
    
    public int peek() {
        dumpstack1();
        return stack2.peek();
    }
    
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    public void dumpstack1() {
        if (!stack2.isEmpty()) return;
        while (!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
    }
}

// 代码未复用
class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;
    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        if (stackOut.isEmpty()) {
            while (!stackIn.isEmpty()) {
                stackOut.push(stackIn.pop());
            }
        }
        return stackOut.pop();
        
    }
    
    public int peek() {
        if (stackOut.isEmpty()) {
            while (!stackIn.isEmpty()) {
                stackOut.push(stackIn.pop());
            }
        }
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }
}
3.复杂度分析

时间复杂度:peek()和pop()为O(n),push()和empty()为O(1).

空间复杂度:O(n).

LeetCode:225. 用队列实现栈 - 力扣(LeetCode)

1.思路

两个队列,一个起到辅助作用,将其作为输出结果的介质,首次进行入队(辅助队列),将结果赋予主队列,返回主队列.

2.代码实现
// 双队列实现
class MyStack {
    
    Queue<Integer> queue1; // 主队列
    Queue<Integer> queue2; // 辅助队列

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        queue2.offer(x);
        while (!queue1.isEmpty()) {
            queue2.offer(queue1.poll());
        }
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }
    
    public int pop() {
        return queue1.poll();
    }
    
    public int top() {
        return queue1.peek();
    }
    
    public boolean empty() {
        return queue1.isEmpty();
    }
}

// 双端队列Deque调方法,nice
class MyStack {
    Deque<Integer> deque;
    public MyStack() {
        deque = new LinkedList<>();
    }
    
    public void push(int x) {   
        deque.push(x);
    }
    
    public int pop() {
        int result = deque.getFirst();
        deque.removeFirst();
        return result;
    }
    
    public int top() {
        return deque.getFirst();
    }
    
    public boolean empty() {
        return deque.isEmpty();
    }
}
3.复杂度分析

时间复杂度:O(1).

空间复杂度:O(1).