1. 程式人生 > 實用技巧 >leetcode-- 棧與佇列

leetcode-- 棧與佇列

模板

用棧模擬佇列

class MyQueue {
    private Stack<Integer> in = new Stack<>();
    private Stack<Integer> out = new Stack<>();

    public void push(int x) {
        in.push(x);
    }

    public int pop() {
        in2out();
        return out.pop();
    }

    public int peek() {
        in2out();
        
return out.peek(); } private void in2out() { if (out.isEmpty()) { while (!in.isEmpty()) { out.push(in.pop()); } } } public boolean empty() { return in.isEmpty() && out.isEmpty(); } }

用佇列模擬棧

//一個棧
class MyStack {
    Queue
<Integer> queueA = new LinkedList<>(); /** Initialize your data structure here. */ public MyStack() {} /** Push element x onto stack. */ public void push(int x) { int len = queueA.size(); queueA.offer(x); for(int i=0;i<len;i++){ queueA.offer(queueA.poll()); } }
/** Removes the element on top of the stack and returns that element. */ public int pop() { return queueA.poll(); } /** Get the top element. */ public int top() { return queueA.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return queueA.isEmpty(); } }