Nina Hain
Nina Hain

Reputation: 41

Reversing a single linked list will only output the first entry (java

I am currently trying to reverse a single linked list through this algorithm:

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

I suspect the issue lies with the swapping of before and current.getNext(), but can't seem to figure it out.

For example, when I input 1 2 3, I receive 3 as an output, but not 3 2 1.

Any help would be greatly appreciated!

EDIT: For those of you asking for more details on the code:

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

Upvotes: 2

Views: 89

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

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

Better readable with nicer naming:

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

Upvotes: 1

Related Questions