请考虑链接列表的以下代码。基本上,我在 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();
}
}