標籤:val ret add color import class style span java
必須做到以下兩點:
1.如果stackPush要往stackPop中壓資料,那麼必須一次性把stackPush中的資料全部壓入。
2.如果stackPop不為空白,stackPush絕對不能向stackPop中壓入資料。
package com.darrenchan;import java.util.Stack;/** * 必須做到以下兩點: * 1.如果stackPush要往stackPop中壓資料,那麼必須一次性把stackPush中的資料全部壓入。 * 2.如果stackPop不為空白,stackPush絕對不能向stackPop中壓入資料。 */public class TwoStackOneQueue { public static Stack<Integer> stackPush; public static Stack<Integer> stackPop; public TwoStackOneQueue(Stack<Integer> stackPush, Stack<Integer> stackPop) { this.stackPush = stackPush; this.stackPop = stackPop; } public static void add(int value){ stackPush.push(value); } public static int poll(){ if(stackPush.isEmpty() && stackPop.isEmpty()){ throw new RuntimeException("Queue is empty!"); }else if(stackPop.isEmpty()){ while(!stackPush.isEmpty()){ stackPop.push(stackPush.pop()); } } return stackPop.pop(); } public static int peek(){ if(stackPush.isEmpty() && stackPop.isEmpty()){ throw new RuntimeException("Queue is empty!"); }else if(stackPop.isEmpty()){ while(!stackPush.isEmpty()){ stackPop.push(stackPush.pop()); } } return stackPop.peek(); } public static void main(String[] args) { TwoStackOneQueue queue = new TwoStackOneQueue(new Stack<Integer>(), new Stack<Integer>()); queue.add(1); queue.add(2); queue.add(3); System.out.println(queue.poll()); System.out.println(queue.peek()); System.out.println(queue.peek()); }}
[演算法]兩個棧實現一個隊列