首页 > 其他 > 详细

143. 重排链表

时间:2020-05-16 13:57:39      阅读:34      评论:0      收藏:0      [点我收藏+]

技术分享图片
技术分享图片
技术分享图片

方法一:

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

143. 重排链表

原文:https://www.cnblogs.com/panweiwei/p/12900086.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!