Reverse a LL

Linked-List Logic Building Medium

Given the head of a singly linked list. Reverse the given linked list and return the head of the modified list.

Examples:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5

Output: head -> 5 -> 4 -> 3 -> 2 -> 1

Explanation: All the links are reversed and the head now points to the last node of the original list.

Input: head -> 6 -> 8

Output: head -> 8 -> 6

Explanation: All the links are reversed and the head now points to the last node of the original list.

This can be seen like: 6 <- 8 <- head.

Input: head -> 1

Constraints

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 104

Hints

  • A brute-force approach would involve: Storing nodes in an array. Reconstructing the linked list from the array in reverse order. Drawback: Uses O(n) extra space, violating the in-place constraint.
  • Use three pointers: prev, current, and next: Initialize prev = NULL, current = head. Iterate through the list, reversing links (current.next = prev). Move prev and current forward. When current becomes NULL, prev points to the new head.

Company Tags

Robinhood Bungie Philips Healthcare Rockstar Games PayPal Mastercard JPMorgan Chase Bain & Company Teladoc Health Roche Broadcom IBM Target AMD Cloudflare Reddit Stripe McKinsey & Company Walmart Epic Systems Zomato DoorDash OYO Rooms Ubisoft Airbnb Google Microsoft Amazon Meta Apple Netflix Adobe