1. 程式人生 > >演算法題016 -- [Implement Queue using Stacks] by java

演算法題016 -- [Implement Queue using Stacks] by java

題目

    使用堆疊實現佇列的以下操作:
  • push(x) - 將元素x推送到佇列的後面。
  • pop() - 從佇列前面刪除元素。
  • peek() - 獲取前面的元素。
  • empty() - 返回佇列是否為空。
    要求:
  • 必須僅使用堆疊的標準操作 - 這意味著只能從頂部新增元素、檢視/彈出;佇列大小,判空空操作是有效的。
  • 由於語言不同,可能不支援原生堆疊。 您可以使用列表或雙端佇列(雙端佇列)來模擬堆疊,只要您只使用堆疊的標準操作即可。
  • 您可以假設所有操作都是有效的(例如,不會在空佇列上呼叫pop或Peek操作)。

分析

對於java而言,也就是使用 Stack 來實現 Queue…
後記:事實上這條題目比我預估的要難一點,用三個 stack 我能解決,用兩個 stack ,參考了別的程式碼,做了點優化…這比用 queue 實現 stack 要難。

思路

在使用兩個 stack 的做法中,其中一個stack是用來記錄需要pop的元素

程式碼

package algorithm016;

import java.util.Stack;

public class Algorithm016 {

	public static void main(String[] args) {
		IQueue<
Integer>
queue = new StackQueue<Integer>(); System.out.println(queue.pop()); System.out.println(queue.peek()); queue.push(4); System.out.println(queue.peek()); System.out.println(queue.pop()); queue.push(1); queue.push(0); System.out.println(queue.pop()); System.out.println
(queue.peek()); queue.push(12); queue.push(2); queue.push(9); queue.push(5); System.out.println(queue.pop()); System.out.println(queue.pop()); } } interface IQueue<E>{ E push(E item); E pop(); E peek(); boolean empty(); } class StackQueue<E> implements IQueue<E> { Stack<E> stackTemp = new Stack<E>(); Stack<E> stack = new Stack<E>(); @Override public E push(E item) { if(item != null) stackTemp.push(item); return item; } @Override public E pop() { if(stack.empty() && stackTemp.empty()) return null; if(stack.empty() && !stackTemp.empty()) peek(); return stack.pop(); } @Override public E peek() { if(stack.empty()) while(stackTemp.size() != 0) { stack.push(stackTemp.pop()); } if(stack.empty() && stackTemp.empty()) return null; return stack.peek(); } @Override public boolean empty() { return stack.empty() && stackTemp.empty(); } }