206. Reverse Linked List LeetCode Solution

In this guide, you will get 206. Reverse Linked List LeetCode Solution with the best time and space complexity. The solution to Reverse Linked List problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Reverse Linked List solution in C++
  4. Reverse Linked List solution in Java
  5. Reverse Linked List solution in Python
  6. Additional Resources
206. Reverse Linked List LeetCode Solution image

Problem Statement of Reverse Linked List

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

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

206. Reverse Linked List LeetCode Solution in C++

class Solution {
 public:
  ListNode* reverseList(ListNode* head) {
    if (!head || !head->next)
      return head;

    ListNode* newHead = reverseList(head->next);
    head->next->next = head;
    head->next = nullptr;
    return newHead;
  }
};
/* code provided by PROGIEZ */

206. Reverse Linked List LeetCode Solution in Java

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

    ListNode newHead = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
  }
}
// code provided by PROGIEZ

206. Reverse Linked List LeetCode Solution in Python

class Solution:
  def reverseList(self, head: ListNode | None) -> ListNode | None:
    if not head or not head.next:
      return head

    newHead = self.reverseList(head.next)
    head.next.next = head
    head.next = None
    return newHead
# code by PROGIEZ

Additional Resources

See also  479. Largest Palindrome Product LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.