我正试图使用上面的listNode类构建链表。有人能帮我如何在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();
}
}
但是,我更希望你使用当您在应用程序中使用链表时,会出现这种情况。