[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/open-source-backup/algo/master/java/09_queue/CircularQueue.java [Back]  [Original]

package queue;

/**
 * Created by wangzheng on 2018/10/9.
 */
public class CircularQueue {
  // itemsn
  private String[] items;
  private int n = 0;
  // headtail
  private int head = 0;
  private int tail = 0;

  // capacity
  public CircularQueue(int capacity) {
    items = new String[capacity];
    n = capacity;
  }

  // 
  public boolean enqueue(String item) {
    // 
    if ((tail + 1) % n == head) return false;
    items[tail] = item;
    tail = (tail + 1) % n;
    return true;
  }

  // 
  public String dequeue() {
    // head == tail 
    if (head == tail) return null;
    String ret = items[head];
    head = (head + 1) % n;
    return ret;
  }

  public void printAll() {
    if (0 == n) return;
    for (int i = head; i % n != tail; ++i) {
      System.out.print(items[i] + " ");
    }
    System.out.println();
  }
}

Web Proxy Viewer  |  New URL  |  Original Page