由两个栈组成的队列

题目:

编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。

思路:

1.新建俩个普通栈,一个栈仅仅压入元素,记为 stackPush ,一个栈仅仅弹出元素,记为 stackPop

2.当一组元素输入时,将该组数据依次压入 stackPush 中,再从压入栈全部取出,依次压入 stackPop 中。 

3.最后,从 stackPop 中依次弹出,就符合了队列的特性:先进先出。 

4.需要注意,如果 stackPush 要往 stackPop 压入数据,那么必须一次性把 stackPush 中的数据全部压入。

5.如果 stackPop 不为空,stackPush 绝对不能向 stackPop 中压入数据。

public class _1_2TwoStacksQueue {
  private Stack stackPush;
  private Stack stackPop;

  public _1_2TwoStacksQueue() {
    stackPush = new Stack<>();
    stackPop = new Stack<>();
  }

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

  public int poll() {
    if (stackPush.empty() && stackPop.empty()) {
      throw new RuntimeException("队列为空!");
    } else if (!stackPop.empty()) {
      while (!stackPush.empty()) {
        stackPop.push(stackPush.pop());
      }
    }
    return stackPop.pop();
  }

  public int peek() {
    if (stackPush.empty() && stackPop.empty()) {
      throw new RuntimeException("队列为空!");
    } else if (!stackPop.empty()) {
      while (!stackPush.empty()) {
        stackPop.push(stackPush.pop());
      }
    }
    return stackPop.pop();
  }
}

注意:

队列    

peek

取出队头元素,不移除 pop 元素出栈,移除
poll 移除队头元素 push 元素入栈
remove 与poll唯一不同,队列为空抛异常 peek 取出栈顶元素,不移除
add 队尾插入元素,失败抛异常    
offer 队尾插入元素,失败返回false    

 

你可能感兴趣的:(数据结构与算法)