143. 重排链表





方法一:

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: None Do not return anything, modify head in-place instead.
        """
        if not head or not head.next:
            return head
        slow, fast = head, head
        pre = head
        # 用快慢指针找链表中间节点,循环结束时:slow.next指向中间节点。
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        # 原链表的后半段
        rev = slow.next
        # 反转原链表的后半段
        behind = None
        while rev:
            temp = rev.next
            rev.next = behind
            behind = rev
            rev = temp
        # 断开原链表的前半段
        slow.next = None
        while pre and behind:
            temp1 = pre.next
            temp2 = behind.next
            pre.next = behind
            behind.next = temp1
            behind = temp2
            pre = temp1
        # return head

方法二思路:

用list统计。

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: None Do not return anything, modify head in-place instead.
        """
        if not head or not head.next:
            return head
        next = []
        pre, cur = head, head

        while pre:
            next.append(pre)
            pre = pre.next
        num = len(next)
        while num > 0:
            cur.next = next[0]
            next.pop(0)
            next = next[::-1]
            cur = cur.next
            num -= 1
        cur.next = None
原文地址:https://www.cnblogs.com/panweiwei/p/12900086.html