下面的代码是我尝试实现SinglyLinkedListNode
和SinglyLinkedList
类,并使用SinglyLinkedListNode reverse(SinglyLinkedListNode head)
方法来反转这个链表。
输入由第一行组成,该行详细说明了测试用例的数量t
。对于每个测试用例,第一行n
表示链表中元素的数量。下一个n
行数将分别包含该列表中的一个元素,这样输入如下:
1 (number of test cases)
5 (number of elements in list)
1 (element in list)
2 (element in list)
3 (element in list)
4 (element in list)
5 (element in list)
我如何修复以下代码,以便它可以打印这个反向链表,以便输出如下:
5 4 3 2 1
相反,我的代码打印出以下内容:
1
5
1
2
3
4
5
1 2 3 4 5
我的代码:
import java.util.Scanner;
public class ReverseLinkedList {
static class SinglyLinkedListNode {
public int data;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(int nodeData) {
data = nodeData;
next = null;
}
}
static class SinglyLinkedList {
private SinglyLinkedListNode head;
private SinglyLinkedListNode tail;
public SinglyLinkedList() {
SinglyLinkedListNode head = null;
SinglyLinkedListNode tail = null;
}
public void insertNode(int nodeData) {
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
public SinglyLinkedListNode reverse(SinglyLinkedListNode head) {
SinglyLinkedListNode previous = null;
SinglyLinkedListNode current = head;
SinglyLinkedListNode next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
public void printLinkedList() {
SinglyLinkedListNode node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SinglyLinkedList list = new SinglyLinkedList();
int testCases = input.nextInt();
if (testCases <= 10) {
input.nextLine();
int size = input.nextInt();
if (size <= 1000) {
for (int i = 0; i < size; i++) {
list.insertNode(input.nextInt());
}
list.reverse(list.tail);
list.printLinkedList();
}
}
}
}
use list.reverse(list.head)
并将您的反向方法修改为
SinglyLinkedListNode previous = null;
SinglyLinkedListNode current = head;
SinglyLinkedListNode next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
head= previous;
return head;
同样在您的方法printLinkedList中设置
SinglyLinkedListNode node = tail; // instead of head
您应该将linkedlist的head而不是tail传递给reverse方法。
list.reverse(list.head);