zoukankan      html  css  js  c++  java
  • LeetCode 92.反转链表-ii

    反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

    说明:
    1 ≤ m ≤ n ≤ 链表长度。

    示例:

    输入: 1->2->3->4->5->NULL, m = 2, n = 4
    输出: 1->4->3->2->5->NULL

    class Solution:
        def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
            """
            input: 1,2,3,4,5,6  (m = 3, n = 5)
            output: 1,2,5,4,3,6
            注意:需要加pre_head 节点,以处理m=1的情况
            """
            if head is None or head.next is None:
                return head
            pre_head = ListNode(None)
            pre_head.next = head
            pre = pre_head
            for _ in range(m - 1):
                pre = pre.next        
            cur = pre.next
            for _ in range(n-m):
                tmp = cur.next
                cur.next = tmp.next
                tmp.next = pre.next
                pre.next = tmp            
            return pre_head.next 
    
    
    """
    class Solution:
        def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
            if head is None or head.next is None:
                return head
            if m == n:
                return head
            node = ListNode(None)
            node.next = head
            left_tail = node
            cur = head 
            cnt = 1
            while cur:
                if cnt == m-1:
                    left_tail = cur
                if cnt == m:
                    mid_head = cur
                    mid_tail = cur 
                if cnt > m:
                    tmp = cur.next 
                    cur.next = mid_head
                    mid_head = cur
                    cur = tmp
                else:
                    cur = cur.next 
                if cnt == n:
                    mid_tail.next = cur 
                    left_tail.next = mid_head
                    break
                cnt+=1
            return node.next 
    """
    
  • 相关阅读:
    3631: [JLOI2014]松鼠的新家
    1112: [POI2008]砖块Klo
    1935: [Shoi2007]Tree 园丁的烦恼
    4001: [TJOI2015]概率论
    1339 / 1163: [Baltic2008]Mafia
    4010: [HNOI2015]菜肴制作
    4052: [Cerc2013]Magical GCD
    2292: 【POJ Challenge 】永远挑战
    4063: [Cerc2012]Darts
    3997: [TJOI2015]组合数学
  • 原文地址:https://www.cnblogs.com/sandy-t/p/13191673.html
Copyright © 2011-2022 走看看