如何用數組模擬一個隊列和一個棧?

1、用數組簡單模擬一個棧

// 基於數組實現的順序棧
public class ArrayStack {
  private String[] items;  // 數組
  private int count;       // 棧中元素個數
  private int n;           // 棧的大小

  // 初始化數組,申請一個大小爲 n 的數組空間
  public ArrayStack(int n) {
    this.items = new String[n];
    this.n = n;
    this.count = 0;
  }

  // 入棧操作
  public boolean push(String item) {
    // 數組空間不夠了,直接返回 false,入棧失敗。
    if (count == n) return false;
    // 將 item 放到下標爲 count 的位置,並且 count 加一
    items[count] = item;
    ++count;
    return true;
  }
  
  // 出棧操作
  public String pop() {
    // 棧爲空,則直接返回 null
    if (count == 0) return null;
    // 返回下標爲 count-1 的數組元素,並且棧中元素個數 count 減一
    String tmp = items[count-1];
    --count;
    return tmp;
  }
}

2、用數組簡單模擬一個隊列

// 用數組實現的隊列
public class ArrayQueue {
  // 數組:items,數組大小:n
  private String[] items;
  private int n = 0;
  // head 表示隊頭下標,tail 表示隊尾下標
  private int head = 0;
  private int tail = 0;

  // 申請一個大小爲 capacity 的數組
  public ArrayQueue(int capacity) {
    items = new String[capacity];
    n = capacity;
  }

  // 入隊
  public boolean enqueue(String item) {
    // 如果 tail == n 表示隊列已經滿了
    if (tail == n) return false;
    items[tail] = item;
    ++tail;
    return true;
  }

  // 出隊
  public String dequeue() {
    // 如果 head == tail 表示隊列爲空
    if (head == tail) return null;
    String ret = items[head];
    ++head;
    return ret;
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章