反转单个链表将只输出第一个条目(java)
我目前正试图通过此算法反转单个链表:
public void reverse() {
Node before = null;
Node current = first;
while (current != null) {
Node next = current.getNext();
before = current;
current = next;
}
first = before;
}
我怀疑问题在于之前和当前的交换。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();
}
}
# 1 楼答案
更好的可读性和更好的命名: