重排链表 -- 每日一题02

'''
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
全部评论

相关推荐

07-11 10:56
门头沟学院 Java
码客明:大胆的说自己能实习6个月就行
点赞 评论 收藏
分享
牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
一表renzha:不是你说是南通我都没往那方面想,人家真是想表达那个意思吗?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:55
点赞 评论 收藏
分享
评论
点赞
7
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务