如何使用定义的 ListNode 将列表作为输入 class

How to take a list as input using the defined ListNode class

我正在尝试使用上面的 listNode class 构建一个链表 class 有人可以帮助我如何获取输入并在 Java 中构建链表 下面是代码:

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

您尝试使用的代码不包含链表所需的函数。 它只是链表中的一个节点。 以下是 Java 中链表的实现,您可以使用:

class Node {
    public int data;
    public Node next;
 
    public void displayNodeData() {
        System.out.println("{ " + data + " } ");
    }
}
 
public class SinglyLinkedList {
    private Node head;
 
    public boolean isEmpty() {
        return (head == null);
    }
 
    // used to insert a node at the start of linked list
    public void insertFirst(int data) {
        Node newNode = new Node();
        newNode.data = data;
        newNode.next = head;
        head = newNode;
    }
 
    // used to delete node from start of linked list
    public Node deleteFirst() {
        Node temp = head;
        head = head.next;
        return temp;
    }
 
    // Use to delete node after particular node
    public void deleteAfter(Node after) {
        Node temp = head;
        while (temp.next != null && temp.data != after.data) {
            temp = temp.next;
        }
        if (temp.next != null)
            temp.next = temp.next.next;
    }
 
    // used to insert a node at the start of linked list
    public void insertLast(int data) {
        Node current = head;
        while (current.next != null) {
            current = current.next; // we'll loop until current.next is null
        }
        Node newNode = new Node();
        newNode.data = data;
        current.next = newNode;
    }
 
    // For printing Linked List
    public void printLinkedList() {
        System.out.println("Printing LinkedList (head --> last) ");
        Node current = head;
        while (current != null) {
            current.displayNodeData();
            current = current.next;
        }
        System.out.println();
    }
}

不过,我希望您使用 this 当您在应用程序中使用链表时。