Reverse a Single Linked List

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Reverse a Single Linked List solution in Java

To reverse a singly LinkedList, we can keep two pointers - one pointing to the currentNode and another pointing to the previous node. Now, we can iterate over the LinkedList, and for every iteration -

  1. Point currentNode.next to the prevNode
  2. Move prevNode to the currentNode
  3. Move currentNode to the nextNode in the LinkedList

Here is the complete solution:

class ListNode {
  int val;
  ListNode next;
  ListNode(int val) {
    this.val = val;
  }
}

class ReverseLinkedListExample {

  private static ListNode reverseLinkedList(ListNode head) {
    ListNode prevNode = null;
    ListNode currentNode = head;
    
    while(currentNode != null) {
        ListNode nextNode = currentNode.next;
        currentNode.next = prevNode;
        prevNode = currentNode;
        currentNode = nextNode;
    }
    return prevNode;
  }

  public static void main(String[] args) {
    ListNode node = new ListNode(1);
    node.next = new ListNode(2);
    node.next.next = new ListNode(3);
    node.next.next.next = new ListNode(4);
    node.next.next.next.next = new ListNode(5);


    ListNode rNode = reverseLinkedList(node);
    while(rNode != null) {
      System.out.print(rNode.val + " ");
      rNode = rNode.next;
    }
    System.out.println();
  }
}
# Output
$ javac ReverseLinkedListExample.java
$ java ReverseLinkedListExample
5 4 3 2 1