I have been attempting to reverse in place a LinkedList in Java 11 using a custom Node class and iteration.
The logic used was to swap the previous and next references of each element in the list in a loop and then subsequently swap the head and tail elements. However the list remains unchanged.
Also it would be hepful to have a toString() method for the Node class but I haven't been able to achieve this.
If anybody can assist with this it will be much appreciated.
My code follows:
import java.util.LinkedList;
public class TEST {
public static void main(String[] args) {
LinkedList<String> strList = new LinkedList<>();
strList.add("one");
strList.add("two");
strList.add("five");
strList.add("four");
strList.add("three");
System.out.println("String list before reversal");
System.out.println(strList);
reverseStringLinkedList(strList);
System.out.println("String list after reversal");
System.out.println(strList);
}
//method to reverse the string linked list
public static void reverseStringLinkedList(LinkedList strList) {
Node head = new Node((String) strList.getFirst());
Node tail = new Node((String) strList.getLast());
Node curr = head;
Node temp;
//swap prev and next references
while (curr != null) {
temp = curr.next;
curr.next = curr.prev;
curr.prev = temp;
curr = curr.prev;
}
//swap head and tail
temp = head;
//DEBUG
System.out.println("temp: " + temp.string);
System.out.println("head: " + head.string);
System.out.println("tail: " + tail.string);
//END DEBUG
head = tail;
tail = temp;
//DEBUG#
System.out.println("AFTER SWAPPING");
System.out.println("head: " + head.string);
System.out.println("tail: " + tail.string);
//END DEBUG
}
}
class Node {
//fields
String string;
Node prev;
Node next;
//constructor
public Node(String string) {
this.string = string;
}
}
LinkedList). Don't do this, always specify the necessary type arguments (i.e.LinkedList<…>).