我正在尝试实现链表,我不知道这段代码有什么问题。 进入无限循环打印1 ...在调用insert()时第一次实例化起始节点
节点
public class Node {
int data;
Node next;
public Node(int data, Node next) {
super();
this.data = data;
this.next = next;
}
public Node()
{
super();
}
}
LinkedList
public class LinkedList {
Node start = null;
void insert(int value)
{
Node current;
current = start;
if(start == null)
{
start = new Node(value, null);
start.data = value;
start.next = null;
}
else
{
while(current.next != null)
{
current = current.next;
}
current.next = new Node();
current.next.data = value;
current.next.next = null;
}
}
void show()
{
Node curr = start;
while(curr.next != null)
{
System.out.println(curr.data);
}
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.insert(1);
ll.insert(7);
ll.insert(5);
ll.insert(3);
ll.insert(9);
ll.show();
}
}
答案 0 :(得分:0)
更改您的show()
方法,如下所示:
void show() {
Node curr = start;
while (curr.next != null) {
System.out.println(curr.data);
curr = curr.next; // This part was missing.
}
}
答案 1 :(得分:0)
在
的while循环中使用curr = curr.next;
答案 2 :(得分:0)
在您的show()
方法中,您错过了:
curr = curr.next
打印当前节点的值后;