Triggered by an interview question (I didn't answer during the interview) I wrote a Java program to reverse a linked list. I went with a loop-based approach instead of recursion. I would like to know the following:
- Is the
reverse()
method efficient as it is, or can it be improved? - Are the inline comments inside the
reverse()
method clear or are they confusing and/or superfluous?
The following is the code for the entire LinkedList
class I wrote, containing a public
reverse()
method:
public class LinkedList<T> { /** * A Node represents a single item inside the linked list. Each node contains * the value of the item and a pointer to the next node. */ class Node { T value; Node next; } /** * The 'head' is the beginning of the linked list. */ Node head; /** * Add an item to the end of the linked list. * * @param value - The value of the item to be added */ public void add(T value) { // Create the new node to be added Node newNode = new Node(); newNode.value = value; // If list is empty, add it at the head if (head == null) { head = newNode; return; } // If the list is not empty, find the end of the list and add it there Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } /** * Perform an in-place reversal of the elements in the linked list. * * After this method is called, the order of the elements in the linked list * will be reversed. */ public void reverse() { Node current = head; // Start at the beginning Node previous = null; // In each iteration, points to the current node's previous node Node next; // In each iteration, we use this to backup the current node's next node while (current != null) { next = current.next; // Backup current node's next node current.next = previous; // Point current node backwards - to the previous node previous = current; // Set new previous to current node, for next iteration head = current; // Point head to current, so by end of loop, it will point to the original tail current = next; // Point current to the original next node, for next iteration } } @Override public String toString() { StringBuilder sb = new StringBuilder(""); Node current = head; while (current != null) { sb.append(current.value + " "); current = current.next; } return sb.toString(); } }
The following is the code I used to test the above method, just in case it is required:
public class LinkedListReversal { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<>(); list.add(1); list.add(2); list.add(3); list.add(4); System.out.println(list); list.reverse(); System.out.println(list); } }
java.util.List
then I would go straight toCollections.reverse()
.\$\endgroup\$