从o开始刷题(2) - 由两个栈组成的队列

95 阅读1分钟

[程序源代码面试指南第二版] 由两个栈组成的队列

需求

两个栈实现队列,实现add poll peek

解题思路

一个stackPush压入新数据,另一个stackPop在弹出时先把stackPush中的数据都压入,然后弹出

一些想法

  1. Stack的isEmpty()和empty()有什么区别

isEmpty()

/**
 * Tests if this vector has no components.
 *
 * @return  {@code true} if and only if this vector has
 *          no components, that is, its size is zero;
 *          {@code false} otherwise.
 */
public synchronized boolean isEmpty() {
    return elementCount == 0;
}

empty()

/**
 * Tests if this stack is empty.
 *
 * @return  <code>true</code> if and only if this stack contains
 *          no items; <code>false</code> otherwise.
 */
public boolean empty() {
    return size() == 0;
}


/**
 * Returns the number of components in this vector.
 *
 * @return  the number of components in this vector
 */
public synchronized int size() {
    return elementCount;
}

附件

public class STACK_fakeQueue {
    private Stack<Integer> stackPush;
    private Stack<Integer> stackPop;

    public STACK_fakeQueue() {
        this.stackPush = new Stack<>();
        this.stackPop = new Stack<>();
    }

    public Stack<Integer> getStackPop() {
        return stackPop;
    }

    public void add(int newNum) {
       this.stackPush.push(newNum);
    }

    public int peek() {
        if (this.stackPush.isEmpty() && this.stackPop.empty()) {
            throw new RuntimeException("stackPop" +
                    "is Empty");
        }
        //isEmpty和empty函数区别
        else if( this.stackPop.isEmpty()) {
            while (!this.stackPush.empty()) {
                this.stackPop.push(this.stackPush.pop());
            }
        }
        return this.stackPop.peek();
    }

    public int poll() {
        if (this.stackPush.isEmpty() && this.stackPop.isEmpty()) {
            throw new RuntimeException("stackPop" +
                    "is Empty");
        }
        else if( this.stackPop.isEmpty()) {
            while (!this.stackPush.isEmpty()) {
                this.stackPop.push(this.stackPush.pop());
            }
        }
        return this.stackPop.pop();
    }
}