剑指offer(五)两个栈实现队列

来源:互联网 发布:美国 大数据公司 data 编辑:程序博客网 时间:2024/06/02 02:59
  • 题目
    • 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
  • 分析
    • 这题没有什么案例,就是用两个栈来完成队列的操作
    • 之前也写过这部分代码,自己找到看了一下,感觉有点不对,于是试了一下,发现真的不通过,正好再完善一下
    • 栈的特性是先进后出,队列呢是先进先出,想用两个栈完成队列的操作还是挺简单的
    • 先将一个栈作为存储,即每次进来都用stack1来进行存储,然后出的时候,将所有stack1的元素一个个放入stack2中
    • 这样,就将元素倒置了,然后再将stack2中元素pop出来,就完成了。
  • 解题代码
import java.util.Stack;public class Solution {    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node) {        if( stack1.isEmpty() )        {            while( !stack2.isEmpty() ){                stack1.push(stack2.pop());            }            stack1.push( node );        } else {            stack1.add(node);        }    }    public int pop() {        if (stack1.isEmpty() && stack2.isEmpty()) {              try {                  throw new Exception("queue is emtry");              } catch (Exception e) {                  e.printStackTrace();              }          }          if( !stack1.isEmpty() ){            while (!stack1.isEmpty()) {                  stack2.push(stack1.pop());              }            return stack2.pop();          }        if( !stack2.isEmpty() ){            return stack2.pop();          }        return 0;    }}
  • 总结
    • 此题难度不大,只要熟悉栈和堆的特性即可
    • 将stack1作为push的集合,stack2作为pop的集合
    • 上述方法将两种职能放到两个方法内,也可在第二个方法pop内,在stack2.pop()执行完之后,立即将元素全部放回stack1中
    • 不过我觉得没必要,各有利弊吧