Reverse linked list

Back to index

From the LeetCode problem with the same name. The problem statement is:

Given the head of a singly linked list, reverse the list, and return the reversed list.

This is not difficult but is an important technique. The idea is to iterate through the list and move each node in turn to the start of the list. Note that we essentially have two pointers in the following solution. One is the head of the list (which is changing!) and one is the next node to transfer to the start.

class Solution {
  public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
      return head;
    }
    ListNode current = head.next;
    head.next = null;
    while (current != null) {
      ListNode tmp = current.next;
      current.next = head;
      head = current;
      current = tmp;
    }
    return head;
  }
}