LeetCode 筆記 - 92. Reverse Linked List II

題目在此 92. Reverse Linked List II

給定一個 Linked list,還有反轉範圍,請反轉其範圍即可

解題思維

如果沒寫過第一題可以看看
LeetCode 筆記 - 206. Reverse Linked List

這題我是偷懶使用 list 來操作,比較簡單一點

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:

data = []

cur_node = head
while cur_node:
data.append(cur_node)
cur_node = cur_node.next

data = data[:left - 1] + list(reversed(data[left - 1: right])) + data[right:]

for i in range(len(data) - 1):
data[i].next = data[i + 1]
data[-1].next = None

return data[0]

也許你也會想看看