本文共 1062 字,大约阅读时间需要 3 分钟。
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型?
import java.util.Stack;public class Solution { Stackstack1 = new Stack (); Stack stack2 = new Stack (); public void push(int node) { stack1.push(node); } public int pop() { //出队列 //判断当前栈是否为空,如果为空,直接抛出异常 if(stack1.isEmpty()&&stack2.isEmpty()){ throw new RuntimeException(); } int number; if(stack2.isEmpty()){ //只有当stack2为空的时候才可以让stack1中的元素进入stack2:原因是假如不加if判断,那么首先从stack1中入栈了两个两个 //元素进stack2,此时pop一个元素,符合队列的先进先出的原则,结果stack2中还有一个元素,如果这个时候再把stack1中的元素加入到stack2中,那么那个 //本来就还在stack2中的元素就被"压住了",而事实上,只有等它也出栈了才能让新的元素进栈。 while(!stack1.isEmpty()){ //如果stack1不为空,把stack1出栈,并且入stack2,相当于调换了一下顺序 number = stack1.pop(); stack2.push(number);//while循环可以就把所有的stack1中的元素放到了stack2当中。 } } return stack2.pop(); }}
push方法入栈,pop方法出栈,isempty判断一个栈是否为空。OVer!
转载地址:http://yrlen.baihongyu.com/