Reverse a Linked List

Coding Solution

·

1 min read

Reverse a Linked List

Problem

Given the head of a singly linked list, reverse the list, and return the reversed list. This is similar to the Leetcode Problem - Reverse Linked List

Approach

The approach would be simple, create a null node, place it to the left of the first node and then reverse all the nodes from the right towards the null node.

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

Do have a look at the discuss section for more optimized solutions if available - LeetCode Discuss