NC21 链表内指定区间反转

描述

将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
例如:
给出的链表为 1\to 2 \to 3 \to 4 \to 5 \to NULL12345NULL, m=2,n=4m=2,n=4,
返回 1\to 4\to 3\to 2\to 5\to NULL14325NULL.

数据范围: 链表长度 0 < size \le 10000<size1000,0 < m \le n \le size0<mnsize,链表中每个节点的值满足 |val| \le 1000val1000
要求:时间复杂度 O(n)O(n) ,空间复杂度 O(n)O(n)
进阶:时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)

示例1

输入:
{1,2,3,4,5},2,4
返回值:
{1,4,3,2,5}

示例2

输入:
{5},1,1
返回值:
{5}
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param m int整型 
# @param n int整型 
# @return ListNode类
#
class Solution:
    def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode:
        # write code here
        p=head
        N=0
        L_lst=[] #利用队列计数
        while p:
            N+=1
            L_lst.append(p)
            p=p.next
        if N<=1:return head
        if m==n:return head
        L1=L_lst[:m-1] if m>1 else None
        L2=L_lst[m-1:n]
        L3=L_lst[n:] if N>n else None
        for i in range(len(L2)-1):
            node=L2[-i-1]
            node.next=L2[-i-2]
        if L3 is not None:
            L2[0].next=L3[0]
        else:
            L2[0].next=None
        if L1 is not None:
            L1[-1].next=L2[-1]
            return L1[0]
        else:
            return L2[-1]

处理算法通用的辅助的code,如读取txt文件,读取xml文件,将xml文件转换成txt文件,读取json文件等
原文地址:https://www.cnblogs.com/tangjunjun/p/15582788.html