如何显示LinkedList的所有内容?

时间:2013-04-27 05:12:43

标签: java data-structures linked-list

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

B
C
null

我想按如下方式显示:     一个     乙     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();



}

}

3 个答案:

答案 0 :(得分:5)

您正在检查curr是否为空,然后递增,这使得curr成为您尝试打印的空值。

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

}

首先进行打印应该会有所帮助。

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

答案 1 :(得分:5)

您的问题出现在DisplayLinkedList的循环中。您“错过”第一个节点,因为您在打印之前前进到下一个节点。

应该是:

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

此外,看起来您正在跟踪prev而不使用它。该方法的简化版本可以是:

public void DisplayLinkedList() {
    Node curr = list;
    while(curr != null) {
        System.out.println(curr);
        curr = curr.getNext();
    }
}

答案 2 :(得分: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);
}