题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

# 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
        # total = 0
        # tmp = head
        # while tmp:
        #     total+=1
        #     tmp = tmp.next
        cur = head
        pre = None
        idx = 0
        while cur:
            tmp = cur.next
            if m==n:
                return head
            if (idx + 1 == m) and (m==1):
                break0 = cur
            if idx + 2 == m:
                break1 = cur
                break2 = cur.next

            if idx < m:
                pre = cur
            else:
                cur.next = pre
                pre = cur


            if idx + 1 == n:

                if m==1:
                    break0.next = tmp
                    return pre
                else:
                    break1.next = cur
                    break2.next = tmp   
                    return head
            cur = tmp
            idx += 1

全部评论

相关推荐

点赞 评论 收藏
分享
喜欢走神的孤勇者练习时长两年半:爱华,信华,等华,黑华
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务