原题
翻转链表中第m个节点到第n个节点的部分
注意事项
m,n满足1 ≤ m ≤ n ≤ 链表长度
样例
给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null
解题思路
- 同Reverse Linked List相似,首先找到四个关键的preM, M, N, postN
完整代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if m == n:
return head
dummy = ListNode(0)
dummy.next = head
prevmNode, nNode = dummy, dummy
for i in range(m - 1):
prevmNode = prevmNode.next
for i in range(n):
nNode = nNode.next
mNode = prevmNode.next
postnNode = nNode.next
prev = postnNode
for _ in range(n - m + 1):
temp = mNode.next
mNode.next = prev
prev = mNode
mNode = temp
prevmNode.next = nNode
return dummy.next