Skip to content

Commit f9dea8e

Browse files
leetcode 206
1 parent bea3fd5 commit f9dea8e

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Leetcode/Leetcode_206.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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

0 commit comments

Comments
 (0)