当我传递节点对象内"top"的节点变量时?它是否有助于它指向以前的数据?



我正在编写一个代码来练习一些具有基础知识的链表示例,但是在voidadd方法的链表类中遇到了问题,当我在节点对象中传递"top"的Node变量时是什么意思? 它有助于它指向以前的数据吗? 我已经指出了涉及我问题的部分

public class Node
{
    private int data;
    private Node nextNode;
    public Node(int dataP , Node nextNodeP)
    {
        data = dataP;nextNode = nextNodeP;
    }
    public int getData()
    {
        return data;
    }
    public Node getNextNode()
    {
        return nextNode;
    }
    public void setData(int newData) //to replace the value of some notes [12| ] --> [120| ]
    {
        data = newData;
    }

    public void setNext(Node newNextNode)  //  pointing to  top ---> [120| ] ---> [last | null]
    {
        nextNode = newNextNode;
    }
 }
 public class LinkedList {
     private Node top;
     private int size;
     public LinkedList() {
         top = null;
         size = 0;
     }
     public int getSize() {
        return size;
     }
     public void addNode(int newData) {
        Node temp = new Node(newData, top); //question 
        top = temp; //points to the same
        size++;
     }
}

在自己的类中定义节点。这里有一个简单的例子:

public class LinkedList {
    private Node first,last;
    private int size ;
    //adds node as last. not null safe
    public void addNode(Node node) {
        if(first == null) {
            node.setParent(null);
            first = node;
            last = node;
        }else {
            node.setParent(last);
            last = node;
        }
        size++;
    }
    public Node getFirst() {return first;}
    public Node getLast() { return last;    }
    public int getSize() {return size;}
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.addNode(new Node(0,null));
        list.addNode(new Node(1,null));
        list.addNode(new Node(2,null));
        list.addNode(new Node(3,null));
        Node node = list.getLast();
        System.out.println("list has "+ list.size + " nodes:");
        while(node != null) {
            System.out.println(node);
            node = node.getParent();
        }
    }
}
class Node{
    private int data;
    private Node parent;
    Node(int nodeData, Node parent) {
        data = nodeData;
        this.parent = parent;
    }
    public int getData() {  return data;}
    public void setData(int data) { this.data = data; }
    public Node getParent() {return parent; }
    public void setParent(Node parent) {this.parent = parent;}
    @Override
    public String toString() {return "Node "+getData() +" parent:"+ getParent();}
}

最新更新