简体   繁体   中英

Inner Class vs Static Inner Class

I am trying to create a linked list implementation using inner class

package linkedlist;

public class linkedList {

public class Node
{
    int data;
    public Node next;
    public Node(int k)
    {
        this.data = k;
        this.next=null;
    }

    public Node addToHead(int data)
    {
        Node node = new Node(data);
        Node current = this;
        node.next=current;
        return node;
    }
}

public static void findn(Node head)
{
    Node previous=head;
    Node current = head;
    int i =1;
    while(current!=null)
    {


                    if (i==6)
        {
            //System.out.println(current.data);
            previous.next = current.next;
            break;
        }
                    previous=current;
                    current = current.next;
                    i++;

    }

}


public static void main(String args[])
{
    linkedList list = new linkedList();
    linkedList.Node tail = linkedList.new Node(0);
//  list.Node tail = list.Node(0);


    Node head = tail;

    for (int i=1;i<=20;i++)
    {
        head = head.addToHead(i);
    }

    findn(head);
    while(head!=null)
    {
        System.out.println(head.data);
        head = head.next;
    }
}
}

My question here in the main function i am trying to create a node using the outer class. But the syntax is throwing me an error even though i am following the right syntax. I want to know what is wrong with this statement "linkedList.Node tail = linkedList.new Node(0);"

A Node, being a non-static inner class, needs an instance of its enclosing class. linkedList is the class name. It doesn't refer to an instance of the class. So it should be

list.new Node()

It would be much clearer if you respected the Java naming conventions: variables start with a lowercase letter, and classes with an uppercase letter.

You should probably create a method within class linkedList, addToTail():

public void addToTail(int k) {
    Node tail = new Node(k);
    //loop through all the nodes in the list and add "tail" to the end
}

Then you can call lst.addToTail(k) in main(), where lst would be an object of class linkedList.

BTW, it makes the code confusing to read when you begin class names with a lowercase letter. They usually start with an uppercase letter in Java. Calling the class LinkedList (starting with caps) is also confusing because it could be mistaken for the standard java.util.LinkedList, so perhaps you could call it LinkedList0 or something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM