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

时间:2015-04-17 13:36:14

标签: java linked-list reverse

我目前正在尝试通过此算法撤消单个链接列表:

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();
}
}

1 个答案:

答案 0 :(得分:1)

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;
}