美文网首页leetcode题解
【Leetcode】143—Reorder List

【Leetcode】143—Reorder List

作者: Gaoyt__ | 来源:发表于2019-07-14 17:13 被阅读0次
    一、题目描述

    给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
    将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
    示例:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.
    
    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
    
    二、代码实现

    三步:1.找到中点 2.逆转后半部分 3.拼接前半部分和逆转过的后半部分

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reverseList(self, cur):
            pre = None
            while cur:
                last = cur.next
                cur.next = pre
                pre = cur
                cur = last
            return pre
        
        def reorderList(self, head):
            """
            :type head: ListNode
            :rtype: None Do not return anything, modify head in-place instead.
            """
            if head == None or head.next == None: return head
            
            fast = head
            slow = head
            
            while fast.next and fast.next.next:
                fast = fast.next.next
                slow = slow.next
                
            newHead = self.reverseList(slow.next)
            slow.next = None
            
            p = head
            while newHead:
                orinext = p.next
                p.next = newHead
                newHead = newHead.next
                p = p.next
                p.next = orinext
                p = p.next
    

    相关文章

      网友评论

        本文标题:【Leetcode】143—Reorder List

        本文链接:https://www.haomeiwen.com/subject/dnhikctx.html