5.两个堆栈实现队列

两个堆栈实现队列;也就是先进先出咯,堆栈取得时候是栈顶,那就将新给的值给栈顶就好了

一个存放,一个倒数就好了;

进来1,放在s1中,s2为空;

进来2,s1为【1】,将s1的值pop()给s2,2赋给s1,再将s2的值pop给s1;

进来3,s1位【1,2】,将s1的值pop()给s2,s1为空,s1赋值,再将s2的值挨个去给s1;

一次类推:……

总体来说还是很简单的,考基础;

import java.util.Stack;public class Solution {

Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
  while(!stack1.empty()) {
    stack2.push(stack1.pop());
  }

  stack1.push(node);

  while(!stack2.empty()) {
    stack1.push(stack2.pop());
  }
}

  public int pop() {
    return stack1.pop();
  }
}

猜你喜欢

转载自www.cnblogs.com/wzQingtTian/p/10661590.html