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

链表内指定区间反转

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

#     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
        
        if head == None or head.next == None or (m ==n):
            return head
        preHead = ListNode(0)
        preHead.next = head  #为了避免对是否从头反转的不同返回情况,创建头节点
        temp = preHead
        start = head
        for i in range(m-1):#顺序到起始反转节点
            temp =temp.next
            start = start.next
            
        temp2 = None
        temp3 = start  #记录m节点,用于最后拼接
        for i in range(n-m+1):  #反转m-n之间节点
            temp4 = start.next
            start.next = temp2
            temp2 = start
            start = temp4

        temp.next = temp2   #首尾拼接
        temp3.next = start
        return preHead.next
全部评论

相关推荐

2 收藏 评论
分享
牛客网
牛客企业服务