Loading...

09-07 leetcode-0092

链接 92. Reverse Linked List II

题目

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

题解

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
38
39
40
41
42
43
from typing import Optional


class ListNode:
def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
self.val = val
self.next = next


class Solution:
def reverseBetween(
self, head: Optional["ListNode"], left: int, right: int
) -> Optional["ListNode"]:
if not head or left >= right:
return head
dummy = ListNode(-1, head)
start, end = dummy, dummy
left_node = None
count = 1
convert_flag = False
while head:
if not convert_flag:
if count == left:
start = end
end, left_node = head, head
convert_flag = True
else:
end = head
head = head.next
else:
temp = head.next
if count == right:
head.next = end
left_node.next = temp
if start:
start.next = head
break
else:
head.next = end
end = head
head = temp
count += 1
return dummy.next

我写会这道题,是不是可以去 Google 了(


Comment