题意: Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
思路:就是把中间部分翻转,再把两边连接上
代码:
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
h = ListNode(0)
h.next = head
p, cnt = h, 1
while 1:
if cnt < m:
p = p.next
elif cnt == m:
t = q = p.next
p.next = None
elif cnt <= n+1:
r = q.next
q.next = p.next
p.next = q
q = r
else:
t.next = q
break
cnt += 1
return h.next