gpt4 book ai didi

java - 反转单链表只会输出第一个条目(java

转载 作者:行者123 更新时间:2023-11-30 11:05:18 25 4
gpt4 key购买 nike

我目前正在尝试通过此算法反转单个链表:

public void reverse() {
Node before = null;
Node current = first;
while (current != null) {
Node next = current.getNext();
before = current;
current = next;
}
first = before;
}

我怀疑问题在于 before 和 current.getNext() 的交换,但似乎无法弄清楚。

例如,当我输入 1 2 3 时,我收到 3 作为输出,但不是 3 2 1。

如有任何帮助,我们将不胜感激!

编辑:对于那些要求了解更多代码细节的人:

class Node {
private int data;
private Node next;

public Node(int newData) {
data = newData;
next = null;
}

public void setNext(Node nextElem) {
next = nextElem;
}

public Node getNext() {
return next;
}

public int getData() {
return data;
}
}

class Element {
public Node first, last;

public void append(int value)
{
Node newElement = new Node(value);
if (first == null)
first = newElement;
else
last.setNext(newElement);
last = newElement;
}

public void output(){
for (Node current = first; current != null; current = current.getNext())
System.out.print(current.getData() + " -> ");
System.out.println();
}

public void reverse() { //the only part I am supposed to change/implement
Node before = null;
Node current = first;
while (current != null) {
Node next = current.getNext();
before = current;
current = next;
}
first = before;
}
}

class LElement {
public static void main(String[] args) {

java.util.Scanner scanner = new java.util.Scanner(System.in);
Element list = new Element();

while (scanner.hasNextInt())
{
list.append(scanner.nextInt());
}
list.output();
list.reverse();
list.output();

scanner.close();
}
}

最佳答案

public void reverse() {
Node before = null;
Node current = first;
while (current != null) {
Node next = current.getNext();
current.setNext(before); ////
before = current;
current = next;
}
first = before;
}

更好的可读性和更好的命名:

public void reverse() {
Node reversedList = null;
Node current = first;
while (current != null) {
Node next = current.getNext();
current.setNext(reversedList); ////
reversedList = current;
current = next;
}
first = reversedList;
}

关于java - 反转单链表只会输出第一个条目(java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700788/

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