Skip to content

Commit 021c27e

Browse files
committed
solve(w07): 206. Reverse Linked List
1 parent b4b027f commit 021c27e

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

reverse-linked-list/seungriyou.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# https://leetcode.com/problems/reverse-linked-list/
2+
3+
from typing import Optional
4+
5+
# Definition for singly-linked list.
6+
class ListNode:
7+
def __init__(self, val=0, next=None):
8+
self.val = val
9+
self.next = next
10+
11+
class Solution:
12+
def reverseList_iter(self, head: Optional[ListNode]) -> Optional[ListNode]:
13+
"""
14+
[Complexity]
15+
- TC: O(n)
16+
- SC: O(1)
17+
18+
[Approach]
19+
linked-list를 reverse 할 때의 핵심은
20+
(1) p1 -> p2를 p1 <- p2로 바꾸고
21+
(2) p1, p2를 모두 한 칸 앞으로 전진
22+
하는 것이다.
23+
이때, (1)에서 p2.next = p1로 바꾼다면, p2를 한 칸 앞으로 전진할 수 없기 때문에 먼저 p2.next(= p3)를 기록해둬야 한다.
24+
이를 iterative 하게 구현하면 while문을 이용할 수 있다.
25+
"""
26+
p1, p2 = None, head
27+
28+
while p2:
29+
# 1. p3 얻어놓기
30+
p3 = p2.next
31+
32+
# 2. p1 <- p2 전환
33+
p2.next = p1
34+
35+
# 3. p1 -> p2, p2 -> p3 이동
36+
p1, p2 = p2, p3
37+
38+
return p1
39+
40+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
41+
"""
42+
[Complexity]
43+
- TC: O(n)
44+
- SC: O(n) (call stack)
45+
46+
[Approach]
47+
linked-list를 reverse 할 때의 핵심은
48+
(1) p1 -> p2를 p1 <- p2로 바꾸고
49+
(2) p1, p2를 모두 한 칸 앞으로 전진
50+
하는 것이다.
51+
이때, (1)에서 p2.next = p1로 바꾼다면, p2를 한 칸 앞으로 전진할 수 없기 때문에 먼저 p2.next(= p3)를 기록해둬야 한다.
52+
이를 recursive 하게 구현하려면 다음과 같이 base condition으로 종료조건을 추가해주면 된다.
53+
"""
54+
55+
def reverse_ll(p1, p2):
56+
# base condition
57+
if not p2:
58+
return p1
59+
60+
# recur
61+
# 1. p3 얻어놓기
62+
p3 = p2.next
63+
64+
# 2. p1 <- p2 전환
65+
p2.next = p1
66+
67+
# 3. p1 -> p2, p2 -> p3 이동
68+
return reverse_ll(p2, p3)
69+
70+
return reverse_ll(None, head)

0 commit comments

Comments
 (0)