92. 反转链表 II
为保证权益,题目请参考 92. 反转链表 II(From LeetCode).
解决方案1
Python
python
# 92. 反转链表 II
# https://leetcode-cn.com/problems/reverse-linked-list-ii/
import itertools
# 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, left: int, right: int) -> ListNode:
h: ListNode = head
nhh: ListNode = None
ntt: ListNode = None
nh: ListNode = None
nt: ListNode = None
# run
for i in itertools.count(1):
if left != 1 and i + 1 == left:
nhh = h
if i == left:
nh = h
if i == right:
nt = h
if i == right + 1:
ntt = h
break
h = h.next
# reversed
def rev(first: ListNode, last: ListNode):
end_tmp_node = last.next
tmp_head = first
ans_head = None
while True:
if ans_head is None:
ans_head = tmp_head
tmp_head = tmp_head.next
else:
next_tmp_head = tmp_head.next
tmp_head.next = ans_head
ans_head = tmp_head
tmp_head = next_tmp_head
if tmp_head is end_tmp_node:
break
rev(nh, nt)
if nhh is None:
h = nt
nh.next = ntt
else:
h = head
nhh.next = nt
nh.next = ntt
return h
if __name__ == "__main__":
node_1 = ListNode(1)
node_2 = ListNode(2)
node_3 = ListNode(3)
node_4 = ListNode(4)
node_5 = ListNode(5)
node_1.next = node_2
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
solution = Solution()
print(solution.reverseBetween(node_1, 2, 4))
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79