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
    
  • 相关阅读:
    [SCOI 2003] 字符串折叠
    [POJ 3252] Round Numbers
    [ZJOI 2010] 数字计数
    [POJ 2282] The Counting Problem
    [POJ 1191] 棋盘分割
    [POJ 3345] Bribing FIPA
    [POJ 2785] 4 Values whose Sum is 0
    [NOIP 2017] 列队
    [NOIP 2017] 宝藏
    基于Qt Gui的Led控制显示程序
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900086.html
Copyright © 2011-2022 走看看