題目:用兩個棧實現隊列
考點:棧和隊列
題目描述:用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
解題思路:每次psuh是時先將stack2清空放入stck1(保證選入的一定在棧底),stack2始終是用來刪除的。在pop前,先將stack1中中的數據清空放入stack2(保存后入的在棧底),stack1始終用於push。
1 import java.util.Stack; 2 3 public class Solution { 4 Stack<Integer> stack1 = new Stack<Integer>(); 5 Stack<Integer> stack2 = new Stack<Integer>(); 6 7 public void push(int node) { 8 //向stack2 push時,先判斷Stack2是否為空, 9 //如果不為空則將stack2的元素出棧,放進stack1中 10 while(!stack2.isEmpty()){ 11 stack1.push(stack2.pop()); 12 } 13 //stack2為空,則直接放入元素 14 stack2.push(node); 15 } 16 17 public int pop() { 18 //棧2元素出棧時先判斷棧1是否為空 19 //如果不為空則將stack1的元素出棧,放進stack2中 20 while(!stack1.isEmpty()){ 21 stack2.push(stack1.pop()); 22 } 23 //棧1為空,此時棧2直接出棧 24 return stack2.pop(); 25 } 26 }