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.
题意:翻转链表m到n。
Runtime: 42 ms
思路:参考206翻转整个链表的思路二,可以m到n视为一个链表,依次将结点放在n后续链表的头结点
注意,指针pm指向m前一结点不变,保证移动的结点始终在pm.next,指针pn指向n结点,保证移动的结点插入的位置始终在n后的头结点
循环次数为n-m次
# 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):
if m==n or not head:
return head
dummy=ListNode(0)
dummy.next=head
pm=pn=dummy
for i in range(m-1):
pm=pm.next
for i in range(n):
pn=pn.next
for i in range(n-m):
t=pm.next
pm.next=pm.next.next
t.next=pn.next
pn.next=t
return dummy.next