首页 > 解决方案 > 为什么 node.next 去下一个节点

问题描述

我是编程新手,目前正在处理链表。我在网上的某个地方得到了这个代码。

public class Node 
{
    Node next;
    int data;

    public Node(int data) 
    {
        this.data=data;
    }

    public class LinkedList
    {    
        Node head;
        public void delete(int data) 
        {    
            Node current=head;
            while (current.next!=null)
            { 
                if (current.next.data==data)
                {
                    current.next= current.next.next;
                }
             }
         }
     }
}

我不明白的是为什么node.next指向下一个节点?在 Node 类中,下一个是数据类型 Node。Node 类中没有 next 方法,但在调用LinkedList该类时current.next,它假定引用下一个节点。

标签: javalinked-list

解决方案


Consider thie code here every node i added in the main method is one object of the class Node and this class contains Node next which is a reference to the next node. For example the first node with value 22 contains a reference to the second node with value 2. For example if you have only one node added the Node next will refer to null because there is no second node. In every node object the Node next reference gives you the next node. But i strongly suggest you to read what is reference in java because you miss a fundamental concepts here.

import java.util.Objects;

class LinkedList<T> {

    private class Node<E> {
        Node<E> next; 
        E val;

        Node(E val) {
            this.val = val;
        }
    }

    private Node<T> head;

    void add(T val) {
        Node<T> node = new Node<>(val);

        if (head == null) {
            head = node;
        } else {
            Node<T> p = head;

            while (p.next != null) {
                p = p.next;
            }

            p.next = node;
        }
    }

    void show() {
        if (head == null)
            return;

        Node<T> p = Objects.requireNonNull(head);

        while (p.next != null) {
            System.out.print(p.val + " ");
            p = p.next;
        }

        System.out.println(p.val);
    }
}

class Main {

    public static void main(String... args) {
        LinkedList<Integer> ll = new LinkedList<>();

        ll.add(22);
        ll.add(2);
        ll.add(4);
        ll.add(32);
        ll.add(3);
        ll.add(1);
        ll.add(44);

        ll.show();

    }
}

推荐阅读