简体   繁体   中英

Linked List Inner Class

I am fairly new to Java and I need to make a linked list. I was told that I need to make a class called "Node" to store each element. I've written the class:

public class Node()
{
    public T data;
    public Node next;

    public Node(T data, Node next)
    {
        this.data = data;
        this.next = next;
    }

    public Node getNext()
    {
        return next;
    }
    public T getData()
    {
        return data;
    }
}

However, I am not allowed to make a separate class, it has to be within the LinkedList class. I understand how to make an inner class of something like an imported iterator, but the "Node" is not imported. How would I do this?

public class Linked{
     class Node{
        int value;
        Node next;
        Node(int data,Node next){
          value=data;
          this.next=next;
        }
        Node getNext(){
         return next;}
        }

//Rest of the linked list methods
}

This is called an inner class which is nothing but a class nested inside another class. When we know that a class has no existence outside the main class we nest that class inside the main class ie as we know that this node class cannot be used outside anywhere in the program thus we made this class an inner class.

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