File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Definition for singly-linked list.
2+ # class ListNode:
3+ # def __init__(self, val=0, next=None):
4+ # self.val = val
5+ # self.next = next
6+
7+ class Solution :
8+ def reverseList (self , head ):
9+ """
10+ Reverse a singly linked list.
11+
12+ Approach:
13+ - Use three pointers: prev, curr (head), and next (implicit)
14+ - Iterate through the list and reverse the direction of each node
15+
16+ Time Complexity: O(n) -> Traverse the list once
17+ Space Complexity: O(1) -> In-place reversal, no extra memory used
18+ """
19+
20+ # 'prev' will become the new head of reversed list
21+ prev = None
22+
23+ # Traverse until head becomes None
24+ while head :
25+ # Step 1: Store current node
26+ curr = head
27+
28+ # Step 2: Move head to next node
29+ # (important to not lose the rest of the list)
30+ head = head .next
31+
32+ # Step 3: Reverse the link
33+ curr .next = prev
34+
35+ # Step 4: Move prev forward
36+ prev = curr
37+
38+ # At the end, prev will be the new head
39+ return prev
You can’t perform that action at this time.
0 commit comments