HOME/剑指Offer/

1.栈和队列

Article Outline
TOC
Collection Outline

1.栈和队列

  • 栈的特点后进先出,队列的特点先进先出
  • 栈是一个不考虑排序的数据结构,需要o(n)的时间才能找到栈中最大或者最小的元素。

1.1题目

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

1.2思路

栈A用来作入队列 栈B用来出队列,当栈B为空时,栈A全部出栈到栈B,栈B再出栈(即出队列)

1.3题解

import java.util.Stack;

public class Solution  {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack1.push(node);
    }
    Integer data = null;
    public int pop() {
        if(stack2.size() <= 0){
         while(stack1.size() > 0){
            data = stack1.pop();
             stack2.push(data);
            } 
        }
        if(!stack2.empty()){
             data = stack2.pop();
        }
        return data;
    }
}