Leetcode 206: Reverse Linked List

grid47
grid47
Exploring patterns and algorithms
Oct 17, 2024 5 min read

A linked list where nodes glow and reverse in position, flowing smoothly backward.
Solution to LeetCode 206: Reverse Linked List Problem

Given the head of a singly linked list, reverse the list and return the new head of the reversed list. You need to reverse the order of the nodes in the list such that the first node becomes the last, the second becomes the second to last, and so on.
Problem
Approach
Steps
Complexity
Input: The input is the head node of a singly linked list where each node contains an integer value and a reference to the next node.
Example: head = [10, 20, 30, 40]
Constraints:
• 0 <= The number of nodes in the list <= 5000
• -5000 <= Node.val <= 5000
Output: Return the head of the new reversed list.
Example: Output: [40, 30, 20, 10]
Constraints:
• The returned list must reflect the reversed order of the nodes.
Goal: The goal is to reverse the linked list and return the head of the newly reversed list.
Steps:
• Initialize two pointers, one for the current node and one for the previous node (which starts as NULL).
• Iterate through the list while the current node is not NULL.
• For each node, change its next pointer to point to the previous node.
• Move both pointers forward to the next node in the original list.
Goal: The solution should work efficiently for any valid singly linked list within the given constraints.
Steps:
• The list may be empty.
• The list may contain up to 5000 nodes.
Assumptions:
• The linked list is well-formed and the input is always valid.
Input: Input: head = [1, 2, 3, 4, 5]
Explanation: In this example, the original list is [1, 2, 3, 4, 5]. After reversing, the new list becomes [5, 4, 3, 2, 1].

Input: Input: head = [10, 20, 30]
Explanation: Here, the input list is [10, 20, 30]. After reversing, the result is [30, 20, 10].

Input: Input: head = []
Explanation: In this case, the input is an empty list, so the output will also be an empty list.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus