zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    邻接表
    分治
    当遇到error: stray '241' in program错误的解决方法
    cmd / msys2 添加到右菜单
    洛谷P1003 铺地毯
    【洛谷P3372】【模板】线段树 1
    【codevs1082】线段树练习 3
    【codevs1081】线段树练习 2
    【codevs1080】线段树练习1
    【洛谷P1731】生日蛋糕
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900086.html
Copyright © 2011-2022 走看看