用隊列實現棧操做

原題

  Implement the following operations of a stack using queues.
  push(x) – Push element x onto stack.
  pop() – Removes the element on top of the stack.
  top() – Get the top element.
  empty() – Return whether the stack is empty.
  Notes:
  You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).java

題目大意

  使用隊列實現棧操做
  push(x) – 元素入棧
  pop() – 元素出棧
  top() – 取棧頂元素值
  empty() – 判斷棧是否爲空
  注意:
  只能使用隊列的標準操做,先進先出,求隊列元素數,判斷隊列是否爲空
  因爲編程語言緣由,有些語言不支撫摩隊列,可使用鏈表或雙向鏈表代替,但僅能使用標準的隊列操做
  你能夠假設全部的操做都是合法的,即:當隊列爲空時不會有元素出棧和求棧頂元素的操做算法

解題思路

  用兩個隊列來模擬一個棧編程

代碼實現

算法實現類編程語言

import java.util.LinkedList;
import java.util.List;

public class MyStack {

    // 維持兩個隊列,其中總有一個隊列爲空,爲pop和top操做準備
    private List<Integer> aList = new LinkedList<>();
    private List<Integer> bList = new LinkedList<>();


    // Push element x onto stack.
    public void push(int x) {
        // 若是aList非空,就將x添加到aList中
        if (!aList.isEmpty()) {
            aList.add(x);
        }
        // 不然總添加到bList中
        else {
            bList.add(x);
        }
    }

    // Removes the element on top of the stack.
    public void pop() {

        // 兩個隊列中至少有一個爲空,將aList設置非空
        if (aList.isEmpty()) {
            List<Integer> tmp = bList;
            bList = aList;
            aList = tmp;
        }

        // 除最後一個元素外都轉移到bList中
        while (aList.size() > 1) {
            bList.add(aList.remove(0));
        }

        // 刪除最後一個元素(對應就是入棧的棧頂元素)
        aList.clear();
    }

    // Get the top element.
    public int top() {

        // 兩個隊列中至少有一個爲空,將aList設置非空
        if (aList.isEmpty()) {
            List<Integer> tmp = bList;
            bList = aList;
            aList = tmp;
        }

        // 除最後一個元素外都轉移到bList中
        while (aList.size() > 1) {
            bList.add(aList.remove(0));
        }

        bList.add(aList.get(0));
        return aList.remove(0);
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return aList.isEmpty() && bList.isEmpty();
    }
}
相關文章
相關標籤/搜索