1. 程式人生 > >劍指offer-05:用兩個棧實現佇列

劍指offer-05:用兩個棧實現佇列

用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。

思路

入隊:將元素進棧A

出隊:判斷棧A是否為空,如果為空,則將棧A中所有元素pop,並push進棧B,棧B出棧;

如果不為空,棧B直接出棧。

程式碼

import java.util.Stack;

public class Solution05 {

    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>
(); public void push(int node) { stack1.push(node); } public int pop() { if(stack1.empty()&&stack2.empty()){ throw new RuntimeException("Queue is empty!"); } if(stack2.empty()){ while(!stack1.empty()){ stack2.
push(stack1.pop()); } } return stack2.pop(); } public static void main(String[] args) { Solution05 solution05=new Solution05(); solution05.push(11); solution05.push(15); solution05.push(8); solution05.push(7); System.out.
printf("pop=%d\r\n",solution05.pop()); System.out.printf("pop=%d\r\n",solution05.pop()); solution05.push(6); solution05.push(5); System.out.printf("pop=%d\r\n",solution05.pop()); System.out.printf("pop=%d\r\n",solution05.pop()); } }

列印

pop=11
pop=15
pop=8
pop=7