带有循环列表的FIFO队列

时间:2016-11-05 17:35:56

标签: java stack queue

我使用单个连接列表创建了一个队列实现。在这段代码中,我使用2个指针(first,last)来定义队列的开始和结束。我的代码是:

import java.io.PrintStream;
import java.util.*
/**
* @author Justin Bieber
*/
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;
}
}

我的问题是如何使用循环列表创建队列实现。 (而不是开始和结束的2个指针,我想只使用一个指针,它将用于队列的开始和结束)。

任何帮助都是相关的。谢谢

0 个答案:

没有答案