gpt4 book ai didi

java - 如何修复以下代码以便获得输出的反向链表?

转载 作者:行者123 更新时间:2023-12-02 08:49:57 24 4
gpt4 key购买 nike

以下代码是我尝试实现 SinglyLinkedListNodeSinglyLinkedList 类,并使用 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

关于java - 如何修复以下代码以便获得输出的反向链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60842971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com