首页 > 编程语言 > 详细

leetcode刷题_PYTHON(15):链表(15) 重排链表

时间:2021-09-13 20:38:27      阅读:30      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 技术分享图片

 

 

解题思路

1、快慢指针找中点,等分成左右两个部分
2、右半部分逆序
3、左右两个部分逐个拼接

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        ##翻转函数
        def reverseList(node: ListNode):
            pre = None
            cur = node
            while cur:
                temp = cur.next   
                cur.next = pre
                pre = cur
                cur = temp
            return pre
        
        #快慢指针找中点
        slow=head
        fast=head
        while fast.next and fast.next.next:
            slow,fast=slow.next,fast.next.next
        
        #右半部分right逆序,左半部分left不动
        reverse_node=slow.next
        right=reverseList(reverse_node)
        slow.next=None
        left=head
        
        #左右两部分逐个拼接+
        while right:
            left=left.next
            head.next=right
            head=head.next
            right=right.next
            head.next=left
            head=head.next

作者:wantingchi
链接:https://leetcode-cn.com/problems/reorder-list/solution/ti-jie-qing-xi-zhi-xing-yong-shi-zai-suo-mhip/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

leetcode刷题_PYTHON(15):链表(15) 重排链表

原文:https://www.cnblogs.com/qiu-hua/p/15259854.html

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