-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSolution.py
37 lines (28 loc) ยท 1.4 KB
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if not head.next: # edge case ์ฒ๋ฆฌ(๋
ธ๋๊ฐ ํ๋๋ผ๋ฉด ๊ทธ๋ฅ ๊ทธ๋๋ก ๋๊ฐ๋ค.
return head
cnt: int = 1 # index ๊ธฐ๋ฐ์ด ์๋ ์์น๊ธฐ๋ฐ์ด๋ผ 1๋ถํฐ ์์
prev, node = None, head # ์์ ๊ฐ ์ค์
while cnt < m: # m๊น์ง cnt ๊ฐ์ ์ฆ๊ฐ์ํค๋ฉฐ ๋
ธ๋๋ฅผ ์์ฐจ์ ์ผ๋ก ํ ๋น
prev, node = node, node.next
cnt += 1
while cnt < n: # n๊น์ง cnt ๊ฐ์ ์ฆ๊ฐ์ํค๋ฉฐ ๋
ธ๋๋ฅผ ์ญ์์ ๋ ฌ
next_node = node.next
if prev: # head๊ฐ ๋ฐ๋์ง ์๋ ๊ฒฝ์ฐ
prev.next, node.next, next_node.next = next_node, next_node.next, prev.next
else: # head๋ถํฐ ๋ฐ๋์ด์ผ ํ๋ ๊ฒฝ์ฐ
head, next_node.next, node.next = next_node, head, next_node.next
cnt += 1
return head
solution: Solution = Solution()
solution.reverseBetween(ListNode(1, ListNode(2, ListNode(3, None))), 1, 3)
solution: Solution = Solution()
solution.reverseBetween(ListNode(3, ListNode(5, None)), 1, 2)
solution: Solution = Solution()
solution.reverseBetween(ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, None))))), 2, 4)