【发布时间】:2016-11-10 16:38:25
【问题描述】:
大家好,我用 java 编写了一个带有 2 个指针(头、尾)的 fifo 队列实现。我想知道是否有任何方法可以创建一个仅使用头指针的先进先出循环队列。任何建议表示赞赏。
我的代码如下:
import java.io.PrintStream;
import java.util.*
public class StringQueueImpl<T> implements StringQueue {
private int total; // number of elements on queue
private Node head; // beginning of queue
private Node tail; // end of queue
private class Node {
T ele;
Node next;
Node(T ele) {
this.ele = ele;
next = null; }
}
/**
* Creates an empty queue.
*/
public StringQueueImpl() {
first = null;
last = null;
total = 0;
}
boolean isEmpty() {
return (head == null);
}
public <T> void put(T ele) {
Node t = tail;
tail = new Node(ele);
if (isEmpty()) head = tail;
else t.next = tail;
total++;
}
public T get() {
if (isEmpty()) throw new NoSuchElementException();
T v = head.ele;
Node t = head.next;
head = t;
return v;
total--;
}
public T peek() {
if (isEmpty()) throw new NoSuchElementException();
return head.ele;
}
Node node = head;
public void printQueue(PrintStream stream){
while(node != null){
stream.println(node.ele);
stream.flush();
node = node.next;
}
}
public int size(){
return total;
}
}
【问题讨论】: