如何显示LinkedList的所有内容?



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

B
C
null

我想显示如下:一个BC

。谁能告诉我在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();

}
}

您正在检查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();
}

您的问题在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();
    }
}
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);
}

相关内容

  • 没有找到相关文章

最新更新