链接列表优先级队列上的无限循环

时间:2016-07-30 22:41:11

标签: java data-structures

在我将第3个值插入队列后,我得到一个无限循环。

插入代码方法:

    public boolean insert(E object) {
    Node<E> Nody = new Node(object);
    Node<E> current = head;
    Node<E> previous = null;
    if (isEmpty())
        head = Nody;
    while (current != null) {
        if (((Comparable<E>) object).compareTo(current.data) >= 0) {
            previous = current;
            current = current.next;
        } else {
            if (((Comparable<E>) object).compareTo(current.data) < 0) {
                previous = Nody;
                Nody = current;
            }
            if (previous == null && ((Comparable<E>) object).compareTo(current.data) < 0) {
                Nody.next = head;
                head = Nody;
            }
        }
    }
    currentSize++;
    return false;
}

这是我使用的驱动程序以及我获得无限循环的地方:

    public P2Driver() {
    list = new OrderedListPriorityQueue<TestInteger>();
    randomInteger = new Random(8);
    randomPriority = new Random(8);

    print("");
    print("/////////////////////////////////////////////////////////");
    print("/// BEGIN TESTING LIST IMPLEMENTATION");
    print("/////////////////////////////////////////////////////////");
    print("");

    // Test insert
    printCurrentSize();
    print("--- BEGIN TESTING INSERT() --- ");
    print("Checking if the list is empty BEFORE insertion...");
    start = System.currentTimeMillis();
    for (int i = 0; i < MAX_SIZE; i++) {
        print(i + ". Is it empty? [ " + list.isEmpty() + " ]");
        list.insert(new TestInteger(randomInteger.nextInt(10)));
    } //GETS STUCK HERE<<<<<<<<<<<<<<<<<

输出:

 /////////////////////////////////////////////////////////
 /// BEGIN TESTING LIST IMPLEMENTATION
 /////////////////////////////////////////////////////////

 Current Size: 0
 --- BEGIN TESTING INSERT() --- 
 Checking if the list is empty BEFORE insertion...
 0. Is it empty? [ true ]
 1. Is it empty? [ false ]
 2. Is it empty? [ false ]

由于没有代码,这意味着驱动程序卡住了。我不确定我做错了什么。

1 个答案:

答案 0 :(得分:1)

while循环中的else语句不会重新定义while循环中使用的当前循环,因此它会卡在那里。