首页 > 其他 > 详细

LeetCode 92.反转链表-ii

时间:2020-06-25 14:27:58      阅读:48      评论:0      收藏:0      [点我收藏+]

反转从位置 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:
        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 

LeetCode 92.反转链表-ii

原文:https://www.cnblogs.com/sandy-t/p/13191673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!