java - 我正在java中实现链表,但我的代码既没有给出任何错误,也没有产生任何输出

标签 java object reference

我正在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/

相关文章:

java - 为什么在 java 中带有监听端口的 TCP/IP 服务器不工作

javascript:使用 EcmaScript 6/immutable js 左合并两个对象

对象的javascript数组推送值

java - 是否可以在 Java 中创建一个对输入法进行计时的方法?

java - Jackcess,具有多个匹配行的循环非常慢,

java - 如何在 Java 中打开 txt 文件并读取数字

oop - 我如何用看似无目标的想法构建面向对象的软件?

python - 为什么在这个函数中使用self?

c++ - 为什么我不能用 `ofstream` 的实例初始化对 `ifstream`/`fstream` 的引用?

java - 如何为 Eclipse Mars 正确设置 JavaFX?