1. 程式人生 > >用棧實現佇列與用佇列實現棧

用棧實現佇列與用佇列實現棧

問題描述

  • 用兩個棧實現佇列
  • 用兩個佇列實現棧

問題分析

  • 用兩個棧實現佇列
    • stackPush 用作 Push 操作,Push 是直接 push 進這個棧。
    • stackPop 用作 Pop 操作,若 stackPop 當前不為空,那麼直接 pop ,若為空,那麼將 stackPush 全部倒入 stackPop 中,然後 stackPop 再 pop 出一個元素
  • 用兩個佇列實現棧
    • 用兩個佇列 queue 佇列 與 help 佇列
    • Push 時直接 push 進 queue佇列
    • Pop 時先檢查queue佇列是否為空,若為空,說明所要實現的棧中不存在元素。若不為空,則將 queue佇列中的元素裝入 help中,queue中只剩最後一個,那麼這便是應該Pop的元素,將該元素pop。pop之後,交換兩佇列,原help佇列作現queue,原queue作現help即可。

程式碼實現

package basic_class_03;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;


public class MyStackAndQueueConvert {
    //用兩個棧實現佇列
    public static class TwoStackQueue{
        private Stack<Integer> stackPush;
        private Stack<Integer> stackPop;

        public
TwoStackQueue() { this.stackPop = new Stack<>(); this.stackPush = new Stack<>(); } public void push (int pushInt) { stackPush.push(pushInt); } public int poll() { if (stackPop.isEmpty() && stackPush.isEmpty()) { throw
new RuntimeException("Queue is empty!"); }else if (stackPop.isEmpty()) { while (! stackPush.isEmpty()) { stackPop.push(stackPush.pop()); } } return stackPop.pop(); } public int peek() { if (stackPop.isEmpty() && stackPush.isEmpty()) { throw new RuntimeException("Queue is empty!"); }else if (stackPop.isEmpty()) { while (! stackPush.isEmpty()) { stackPop.push(stackPop.pop()); } } return stackPop.peek(); } } //用兩個佇列實現棧 public static class TwoQueuesStack{ private Queue<Integer> queue; private Queue<Integer> help; public TwoQueuesStack() { queue = new LinkedList<>(); help = new LinkedList<>(); } public void push(int pushInt) { queue.add(pushInt); } public int peek() { if (queue.isEmpty()) { throw new RuntimeException("Stack is empty!"); } while (queue.size() != 1) { help.add(queue.poll()); } int res = queue.poll(); help.add(res); swap(); return res; } public int pop() { if (queue.isEmpty()) { throw new RuntimeException("Stack is empty!"); } while (queue.size() != 1) { help.add(queue.poll()); } int res = queue.poll(); swap(); return res; } public void swap() { Queue<Integer> temp = queue; queue = help; help = temp; } } }