使用链接列表实现队列,Enqueue()无法正常工作

时间:2014-07-24 20:25:29

标签: java linked-list

public class Queue implements QueueInterface {

private class Node {
    Object data;
    Node next;

    Node(Object data) {
        this.data = data;
        // this.next = next;
    }
}

private Node head;
private Node tail;
private int  count;

// isEmpty()
// pre: none
// post: returns true if this Queue is empty, false otherwise
public boolean isEmpty() {
    return head == null;
}

 // enqueue()
// adds newItem to back of this Queue
// pre: none
// post: !isEmpty()
public void enqueue(Object newItem) {

    Node p = new Node(newItem);

    if (isEmpty()) {
        head = tail = p;
    } else {
        tail.next = p;
        p = tail;
    }

}
// toString()
// overrides Object's toString() method
public String toString() {
    String s = "";
    for (Node N = head; N != null; N = N.next) {
        s += N.data + " ";
    }
    return s;
}
 }

当我使用队列测试java文件时。我尝试将数字2,5,7和10排入队列。但是当我想打印出元素时,它只显示第一个和最后一个元素。

我不知道我的toString函数是否正常工作,或者它是否为enqueue .-。

1 个答案:

答案 0 :(得分:1)

enqueue应将tail更新为新排队的元素:

public void enqueue(Object newItem) {

    Node p = new Node(newItem);

    if (isEmpty()) {
        head = tail = p;
    } else {
        tail.next = p;
        tail = p;  // instead of p = tail;
    }

}

public String toString() {
    // Use a StringBuilder instead of String
    StringBuilder sb = new StringBuilder();
    for (Node N = head; N != null; N = N.next) {
        sb.append(N.data + " ");
    }
    return sb.toString();
}