Question

I need to know how to reverse my linked list.

I will post my Node and LinkedList classes. The other two are the driver (which creates an instance of my TUI class and my TUI class which asks the user which word to add to the LinkedList and then prints the list and reverses it (by calling the reverse method in LinkedList which is what I need help on)

I don't know what to write for reverse method in my LinkedList

Node Class:

public class Node {

private String data;
private Node next;

public Node(String data, Node next) {
    this.data = data;
    this.next = next;
}

public Node(String data) {
    this.data = data;
    this.next = null;
}

public String getData() {
    return this.data;
}
public Node getNext() {
    return this.next;
}

public void setNext(Node nextNode) {
    this.next = nextNode;
}

public String toString() {
    return this.data;
}
}

Linked List class:

public class LinkedList {

private Node head;
private Node tail;

public LinkedList() {
    this.head = null;
    this.tail = null;
}

public void prepend(String data) {
    Node newNode = new Node(data, this.head);
    if (this.head == null) {
        this.head = newNode;
        this.tail = newNode;
    } else {
        this.head = newNode;
    }
}

public void printList() {
    Node current = this.head;

    while (current != null) {
        System.out.println(current.getData());
        current = current.getNext();
    }
}

public void append(String data) {
    Node newNode = new Node(data);

    if (this.head == null) {
        this.head = newNode;
        this.tail = newNode;
    } else {
        this.tail.setNext(newNode);
        this.tail = newNode;
    }
}

public void reverse() {

}
}
Était-ce utile?

La solution

This should do the job. The idea is that for each list node, temporarily copy its next node, set its next to the previous node, and set the previous node to it. It can also be done recursively.

public void reverse() {
    Node prev = null;
    Node current = head;
    while (current != null) {
        Node next = current.getNext();
        current.setNext(prev);
        prev = current;
        current = next;
    }
    this.head = prev;
}

Edit: you will also need to update the tail reference

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top