How is a linked list defined in Java?

In Java, a linked list can be defined using the following method:

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

This is a basic node class for a linked list, which includes an integer value and a pointer to the next node.

Then, this node class can be used to create a linked list as shown below:

public class LinkedList {
    ListNode head;

    public void add(int val) {
        ListNode newNode = new ListNode(val);
        if (head == null) {
            head = newNode;
        } else {
            ListNode current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    public void display() {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }
}

The LinkedList class in the above code implements the functions of adding nodes and displaying the linked list. The add method is used to add a new node to the linked list, and the display method is used to print all the nodes in the linked list.

You can use the following code to test the usage of linked lists:

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(2);
        list.add(3);

        list.display(); // 输出:1 2 3
    }
}

Running the above code will output the values of all nodes in the linked list.

bannerAds