Skip to content

Commit 78dae2d

Browse files
committed
reverse linked list solution
1 parent 508129a commit 78dae2d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
3+
# iterative way
4+
5+
"""
6+
prev, curr = None, head
7+
while curr:
8+
tmp_nxt = curr.next
9+
10+
curr.next = prev
11+
prev, curr = curr, tmp_nxt
12+
13+
return prev
14+
"""
15+
16+
# Recursive Way
17+
if head is None or head.next is None:
18+
return head
19+
20+
new_head = self.reverseList(head.next)
21+
head.next.next = head # reversing pointer
22+
head.next = None
23+
return new_head
24+
25+
# λ‘˜ λ‹€ μ‹œκ°„λ³΅μž‘λ„ O(n)
26+
# ν•˜μ§€λ§Œ μž¬κ·€μ˜ 경우 μ½œμŠ€νƒμ— λ”°λ₯Έ κ³΅κ°„λ³΅μž‘λ„ O(n)을 μ†Œμš”
27+
# iterative 방식은 O(1)
28+
29+

0 commit comments

Comments
Β (0)