题目
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
思路
进行一遍遍历,把第m到n个元素进行翻转,即依次插入到第m个节点的头部。
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
count = 1
root = ListNode(0)
root.next = head
pre = root
while pre.next and count < m:
pre = pre.next
count += 1
if count < m:
return head
mNode = pre.next
curr = mNode.next
while curr and count < n:
next = curr.next
curr.next = pre.next
pre.next = curr
mNode.next = next
curr = next
count += 1
return root.next