题解 | #重排链表#

重排链表

https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

'''
1、先使用快慢指针遍历链表,当快指针下一次要到结尾时,慢指针在链表中点
2、此时慢指针指的即是链表的中点,也是我们重排序的终点,置空慢指针的下一个,并反转后面的链表
3、合并俩个链表 head,n_head
'''
class Solution:
    def reorderList(self, head):
        # write code here
        # 123456  162534
        if head==None or head.next==None or head.next.next==None:
            return head
        slow = head
        quick = head

        while quick.next is not None and quick.next.next is not None:
            slow = slow.next
            quick = quick.next.next
        # 慢指针刚好在中点
        # 反转后半部分
        n_head = slow.next
        slow.next = None
        n_head = self.resolve(n_head)
        
        while n_head is not None:
            temp = n_head.next
            n_head.next = head.next
            head.next = n_head
            head = n_head.next
            n_head = temp


    def resolve(self, head):
        if head is None:
            return head
        tail = head # 取出第一个
        head = head.next
        tail.next = None
        while head is not None:
            p_node = head.next
            head.next = tail
            tail = head
            head = p_node
        return tail

全部评论

相关推荐

ResourceUtilization:四六级不愧是大学最有用的证之一
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务