当前位置: 动力学知识库 > 问答 > 编程问答 >

java - LinkedList without tail field gets stuck in infinite loop

问题描述:

What's wrong with my LinkedList add method if I want to implement it without a tail field?

public class LinkedList<E> {

private Node<E> head= new Node<E>();

private int size=0;

public void linkedList(){

head=null;

size=0;

}

public void add(E data){

Node<E> currNode=head;

while (currNode.hasNext()){

currNode.setNext(currNode.getNext());

}

Node<E> lastNode= new Node<E>();

lastNode.setItem(data);

lastNode.setNext(null);

currNode.setNext(lastNode);

size++;

}

public void remove(int i){

Node<E> currNode = head;

int index=0;

while (index<i){

currNode.setNext(currNode.getNext());

i++;

}

currNode.setNext(currNode.getNext().getNext());

}

public void print(){

Node<E> currNode = new Node<E>();

do{

System.out.println(currNode.getItem());

} while (!currNode.hasNext());

}

public static void main(String arc[]){

LinkedList<String> ll = new LinkedList<String>();

ll.add("9");

ll.add("b");

ll.add("987");

ll.print();

return;

}

}

Here's the Node class:

public class Node<E> {

private E item;

private Node<E> next;

public Node<E> getNext(){

return this.next;

}

public void setNext(Node<E> n){

this.next=n;

}

public E getItem(){

return this.item;

}

public void setItem(E item){

this.item=item;

}

public boolean hasNext(){

return (this.next != null);

}

}

Edit: Changed the print method to:

public void print(){

Node currNode = head;

 while (currNode.hasNext()){

System.out.println(currNode.getItem());

currNode=currNode.getNext();

}

}

and I get this result:

null

9

b

网友答案:

In your add method, don't you mean :

currNode = currNode.getNext();

instead of :

currNode.setNext(currNode.getNext());

? Because the last one has no effect and you are making an infinite loop...

网友答案:

This block will never end

while (currNode.hasNext()) {
    currNode.setNext(currNode.getNext());
}

So infinite loop.

Make sure you move the currNode to forward, to reach the loop end by adding crrNode.next() inside the while loop.

分享给朋友:
您可能感兴趣的文章:
随机阅读: