题目:
反转链表 II:反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:输入: 1->2->3->4->5->NULL, m = 2, n = 4输出: 1->4->3->2->5->NULL
思路:
思路较简单,找到规律就好。
程序:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if not head:
return head
if m >= n:
return head
myNode = ListNode(0)
myNode.next = head
index1 = myNode
num_rotate = n - m
while m - 1:
index1 = index1.next
m -= 1
index2 = index1.next
index3 = index2.next
while num_rotate:
index2.next = index3.next
index3.next = index1.next
index1.next = index3
index3 = index2.next
num_rotate -= 1
return myNode.next