1

请考虑链接列表的以下代码。基本上,我在 LinkedList 类中创建了三个节点并尝试显示内容,但我在 DisplayLinkedList() 方法中做错了。现在我得到如下输出:

B
C
null

我想显示如下:A B C

分别。谁能告诉我 DisplayLinkedList() 方法哪里错了?

package MyPackage;


class Node {

String data;
Node next;

public Node(String data, Node next){

    this.data = data;
    this.next = next;

}

public String getData(){
    return data;
}

public Node getNext(){

    return next;
}

public void setNext(Node n){
    next = n;
}

 public String toString() {
     return this.data;
 }


}

// CREATING LINKED LIST BACKWARDS AND APPLYING SOME OPERATIONS ON IT


class LinkedList{

Node cNode = new Node("C", null);

Node bNode = new Node("B", cNode);

Node list = new Node("A", bNode);


public void DisplayLinkedList(){

    Node prev = null;
    Node curr = list;

    while(curr != null){

        prev = curr;
        curr = curr.getNext();
        System.out.println(curr);

    }


}




public class LinkedListByME {


public static void main(String[] args) {


    LinkedList ll = new LinkedList();
    ll.DisplayLinkedList();



}

}
4

3 回答 3

5

You're checking if the curr is null, and THEN incrementing, which makes curr a null value that you try to print.

while(curr != null){
    prev = curr;
    curr = curr.getNext();
    System.out.println(curr);

}

doing the print first should help.

while(curr != null){
    System.out.println(curr);
    prev = curr;
    curr = curr.getNext();
}
于 2013-04-27T05:15:58.070 回答
5

Your issue is in your loop in DisplayLinkedList. You "miss" the first node because you advance to the next node before printing it.

It should be:

while(curr != null) {
   System.out.println(curr);
   prev = curr;
   curr = curr.getNext();    
}

Also, it looks like you are keeping track of prev without using it. The simplified version of the method could be:

public void DisplayLinkedList() {
    Node curr = list;
    while(curr != null) {
        System.out.println(curr);
        curr = curr.getNext();
    }
}
于 2013-04-27T05:16:06.493 回答
0
public void listTrasverse() {
    if(isEmpty()) {
        System.out.print("\nLIST IS EMPTY !!!");
    } else {
        while(current!=null) {
            current.displayLink();
            current=current.next;
        }
    }
}

使用此代码调用displayLink()节点类中的方法,该displayLink()方法将是

public void displayLink(){
    System.out.print("\nDATA= "+data);
}
于 2013-04-27T05:48:36.020 回答