143._reorder_list.md 2.2 KB
Newer Older
K
KEQI HUANG 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
###143. Reorder List

题目:

<https://leetcode.com/problems/reorder-list/>


难度:

Medium

超时


```

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        head = self.reorder(head)

        
    def reorder(self, head):
        if head == None or head.next == None or head.next.next == None:
            return head
    
        l0 = head
        l1 = head.next
        ln_1 = self.oneNodeTail(head)
        ln =ln_1.next
    
        l0.next = ln
        ln_1.next = None
        ln.next = self.reorder(l1)
        return l0
        

    def oneNodeTail(self, head):
        if head == None or head.next == None or head.next.next == None:
            return head
        cur = head 
        while cur.next:
            if cur.next.next:
                cur = cur.next
            else:
                break
        return cur
                
```


取巧的办法是:

找到中间节点,断开,把后半截linked list reverse,然后合并 √

看了AC指南

```
class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if head == None or head.next == None or head.next.next == None:
            return
        
        slow = head
        fast = head
        prev = None
        
        while fast and fast.next:
            prev = slow
            slow = slow.next
            fast = fast.next.next
            
        prev.next = None


        slow = self.reverseList(slow)
        
        cur = head
        while cur.next:
            tmp = cur.next
            cur.next = slow
            slow = slow.next
            cur.next.next = tmp
            cur = tmp
        cur.next = slow
            
        
    
    def reverseList(self,head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None 
        cur = head
        while(cur):
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
        return prev
        
        
```