我的代码问题是,当我运行代码时,list1st元素会自动复制到ll节点上。

问题描述 投票:-2回答:1

我的代码问题是,当我运行代码时,list1st元素会自动复制到ll节点上。

用于实现链接列表的一个类。

public class node {

    static public class Node{
        Node next;
        int data;
        Node(int d)
        {
            this.data=d;
            this.next=null;
        }
        static Node head=null;
        public void add(int data)
        {
             Node new_node = new Node(data); 
                new_node.next = head; 
                head = new_node; 

        }
public void printlist(Node list) {

             Node currNode = list.head; 

                System.out.print("Linked List: "); 

                // Traverse through the Linked List 
                while (currNode != null) { 
                    // Print the data at current node 
                    System.out.print(currNode.data + " "); 

                    // Go to next node 
                    currNode = currNode.next; 
                } 
                System.out.println(" ");
        }
}
}

第二个类用于链接列表的工作

    public class Linked_list {
        public static void main(String args[])
        {
            Node list1=new Node(0);*// 1st linked list*
            list1.add(10);
            list1.add(1);
            list1.add(15);
            list1.add(3);
            list1.add(88);
            list1.printlist(list1);
            Node ll=new Node(0);   **//second linked list**
            ll.add(55);
            ll.add(44);
            ll.printlist(ll);
        }

 }

我的代码问题是,当我运行代码时,list1st元素会自动复制到ll节点上。

java list printing add implementation
1个回答
0
投票

你的代码有很多问题。主要的错误在你的类中 Node:

static Node head=null;

外地 head 不可 static. 把它改成这样。

private Node head = null;

你还需要修改代码的其余部分来设置 head 适当地变 add 方法应该返回新创建的 Node 而不是 void以及在 main 方法,你需要使用返回值。

为什么要把它做成 static因为 static 使其成为类级变量,由类的所有实例共享,而这不是你想要的。

更多信息。了解类成员

另外, printlist 方法不需要取一个 Node 作为一个论据。只要让它在 Node 你调用它。


0
投票

正如 @Jesper 先生所解释的那样,这对我来说是非常有益的,我也通过将公共静态头改为私有头来修正我的代码。

谢谢你,先生

© www.soinside.com 2019 - 2024. All rights reserved.