How to create a singly linked list in Java?

To create a singly linked list in Java, you can implement it by creating a node class and a linked list class. The specific steps are as follows:

Firstly, create a node class to represent the nodes in the linked list. The node class should contain a data field and a pointer to the next node.

class ListNode {
    int data;
    ListNode next;

    public ListNode(int data) {
        this.data = data;
        this.next = null;
    }
}

Next, create a linked list class to handle the operations of the linked list. The linked list class will have a head node and basic methods such as adding nodes, deleting nodes, and so on.

class LinkedList {
    ListNode head;

    public LinkedList() {
        this.head = null;
    }

    // 添加节点
    public void addNode(int data) {
        ListNode newNode = new ListNode(data);
        if (head == null) {
            head = newNode;
        } else {
            ListNode currentNode = head;
            while (currentNode.next != null) {
                currentNode = currentNode.next;
            }
            currentNode.next = newNode;
        }
    }

    // 打印链表
    public void printList() {
        ListNode currentNode = head;
        while (currentNode != null) {
            System.out.print(currentNode.data + " ");
            currentNode = currentNode.next;
        }
    }
}

Finally, create a linked list object in the main function and call the relevant methods to manipulate the linked list.

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.addNode(1);
        list.addNode(2);
        list.addNode(3);
        list.printList();  // 输出:1 2 3
    }
}

By following the above steps, you can create a singly linked list in Java.

bannerAds