用兩個棧來實現一個隊列
阿新 • • 發佈:2018-06-25
8K turn 圖片 node 技術 空間 sem str import
題目:
用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型
限制:
時間限制:1秒 空間限制:32768K 熱度指數:240468
1 package com.algorithm; 2 3 import java.util.Stack; 4 5 /** 6 * 用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型 7 * @日期:2018年6月24日 下午9:17:49 8 * @作者:Chendb 9 */ 10 public class Queue { 11 12 Stack<Integer> stack1 = newView CodeStack<Integer>(); 13 Stack<Integer> stack2 = new Stack<Integer>(); 14 15 public static void main(String[] args) { 16 Queue queue = new Queue(); 17 //System.out.println(queue.pop()); 18 queue.push(1); 19 queue.push(3); 20 21 System.out.println(queue.pop());22 queue.push(2); 23 24 System.out.println(queue.pop()); 25 System.out.println(queue.pop()); 26 } 27 28 public void push(int node) { 29 stack1.push(node); 30 } 31 32 public int pop() { 33 stack2.clear(); 34 35 while(!stack1.isEmpty()) { 36 stack2.push(stack1.pop()); 37 } 38 39 if (stack2.isEmpty()) { 40 return 0; 41 } 42 43 int result = stack2.pop(); 44 45 while (!stack2.isEmpty()) { 46 stack1.push(stack2.pop()); 47 } 48 49 return result; 50 } 51 52 }
用兩個棧來實現一個隊列