我正在java中实现链表,但我的代码既没有给出任何错误,也没有产生任何输出。
class LinkedList25
{
Node head;
class Node
{
int data;
Node next;
Node(int value)
{
data = value;
next = null;
}
}
public static void main(String args[])
{
LinkedList25 list = new LinkedList25();
boolean choice = true;
list.insertNode(1,list.head);
list.insertNode(2,list.head);
list.insertNode(3,list.head);
list.printList(list.head);
}
public void insertNode(int value,Node move)
{
Node temp = new Node(value);
temp.next = move;
move = temp;
}
public void printList(Node move)
{
while(move!=null)
{
System.out.print(move.data+"->");
}
}
}
最佳答案
多次观察
首先,list.head 没有初始化,即使 insertNode 方法中的 move 变量被分配了对新节点的引用,它也是按值传递的,因此它不会将更新的引用反射(reflect)回 main 方法中的 list.node 。您可以更新 insertNode 方法以返回 Node 并返回“移动”回 main 方法并将返回值分配给 list.head。如下
// in main
list.head = list.insertNode(1, list.head);
list.head = list.insertNode(2, list.head);
list.head = list.insertNode(3, list.head);
// in insertNode method return the move node back to caller
public Node insertNode(int value, Node move) {
Node temp = new Node(value);
temp.next = move;
move = temp;
return move;
}
第二个 printList 方法进入无限循环,因为移动未遍历到下一个节点
// in printList method add move = move.next inside the while loop as below
public void printList(Node move) {
while (move != null) {
System.out.print(move.data + "->");
move = move.next; // ADD THIS LINE TO AVOID INFINTE LOOP
}
}
上述更改应该可以解决并打印列表。
有一个问题,在当前代码中,链表的行为就像一堆值,因为新值总是插入到头部之前。因此 printList 方法将以插入值的相反顺序打印值。
如果目的是堆栈,则 insertNode 方法的正确方法是
public void insertNode(int value) {
Node temp = new Node(value);
if (this.head == null) {
this.head = temp;
} else {
temp.next = this.head;
this.head = temp;
}
}
如果 LinkedList 的目的不是作为堆栈,而是按照添加顺序存储值,则 insertNode 方法应如下所示
public void insertNode(int value) {
Node temp = new Node(value);
if (this.head == null) {
this.head = temp;
} else {
Node par = this.head;
while (par.next != null) {
par = par.next;
}
par.next = temp;
}
}
在main方法中,不需要总是传递list.head,因为insertNode方法可以直接访问head,如下所示。
list.insertNode(1);
list.insertNode(2);
list.insertNode(3);
关于java - 我正在java中实现链表,但我的代码既没有给出任何错误,也没有产生任何输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017424/