【劍指offer第五題】用兩個棧實現佇列
阿新 • • 發佈:2018-12-13
棧的實現是先進後出,佇列是先進先出。思路就是第一個棧的元素按次序出棧,然後第二個棧依次入棧,然後出棧。
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); //佇列的入隊方法,首先將入隊元素倒序壓入棧1 public void push(int node) { stack1.push(node); } //佇列的出隊方法 public int pop() { int result;//佇列的出隊元素 if(stack2.isEmpty()){//當棧2為空時,將棧1的元素出棧,壓入棧2 while(!stack1.empty()){ stack2.push(stack1.pop());//棧1棧頂出棧,同時棧2入棧 } } result=stack2.pop();//棧2出棧 return result; } }