Skip to content

Commit b98d68c

Browse files
committed
Solve: Reverse Linked List
1 parent 83f538a commit b98d68c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Constraints:
3+
- The number of nodes in the list is the range [0, 5000]
4+
- -5000 <= Node.val <= 5000
5+
6+
Time Complexity: O(n)
7+
- n์€ linked list์˜ ๋…ธ๋“œ ์ˆ˜
8+
- ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•œ ๋ฒˆ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ๋งŒ ๋ฐฉ๋ฌธํ•˜๊ธฐ ๋•Œ๋ฌธ
9+
10+
Space Complexity: O(1)
11+
- ์ถ”๊ฐ€ ๊ณต๊ฐ„์œผ๋กœ prev, curr, temp ์„ธ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋งŒ ์‚ฌ์šฉ
12+
- ์ž…๋ ฅ ํฌ๊ธฐ์™€ ๊ด€๊ณ„์—†์ด ์ผ์ •ํ•œ ์ถ”๊ฐ€ ๊ณต๊ฐ„๋งŒ ์‚ฌ์šฉ
13+
14+
ํ’€์ด ๋ฐฉ๋ฒ•:
15+
1. ์„ธ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๋’ค์ง‘๊ธฐ
16+
- prev: ์ด์ „ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ํฌ์ธํ„ฐ
17+
- curr: ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ํฌ์ธํ„ฐ
18+
- temp: ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ์ž„์‹œ ์ €์žฅํ•˜๋Š” ํฌ์ธํ„ฐ
19+
20+
2. ๊ฐ ๋‹จ๊ณ„์—์„œ:
21+
- ๋‹ค์Œ ๋…ธ๋“œ ์ž„์‹œ ์ €์žฅ (temp)
22+
- ํ˜„์žฌ ๋…ธ๋“œ์˜ next๋ฅผ ์ด์ „ ๋…ธ๋“œ๋กœ ๋ณ€๊ฒฝ
23+
- ํฌ์ธํ„ฐ๋“ค์„ ํ•œ ์นธ์”ฉ ์ „์ง„
24+
25+
3. ์ฐธ๊ณ :
26+
- ํฌ์ธํ„ฐ๋“ค์˜ ์ด๋™ ์ˆœ์„œ๊ฐ€ ์ค‘์š”
27+
- prev๊ฐ€ ์ƒˆ๋กœ์šด head๊ฐ€ ๋จ
28+
"""
29+
30+
# Definition for singly-linked list.
31+
# class ListNode:
32+
# def __init__(self, val=0, next=None):
33+
# self.val = val
34+
# self.next = next
35+
class Solution:
36+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
37+
prev = None
38+
curr = head
39+
40+
while curr is not None:
41+
42+
temp = curr.next
43+
curr.next = prev
44+
prev = curr
45+
curr = temp
46+
47+
return prev

0 commit comments

Comments
ย (0)