牛客——链表指定区间翻转

牛客——链表指定区间翻转_第1张图片

# 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 , m , n ):
        # write code here
        Head = ListNode(0)
        Head.next = head
        p = head
        q = head
        pre = Head
        for _ in range(m-1):
            pre = p
            p = p.next
        for _ in range(n-1):
            q = q.next
        last = q.next
        pre.next = last
        
        q.next = None
        rev = self.ReverseList(p)  # 反转链表
        p_rev = rev
        while p_rev.next:
            p_rev = p_rev.next
        p_rev.next = last
        pre.next = rev
        return Head.next
        
    def ReverseList(self, pHead):
        # write code here
        pre = None
        while pHead:
            next = pHead.next
            pHead.next = pre
            pre = pHead
            pHead = next
        return pre

反转链表

牛客——链表指定区间翻转_第2张图片

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        pre = None
        while pHead:
            next = pHead.next
            pHead.next = pre
            pre = pHead
            pHead = next
        return pre

你可能感兴趣的:(算法刷题笔记)