zoukankan      html  css  js  c++  java
  • 143. Reorder List

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

    You may not modify the values in the list's nodes, only nodes itself may be changed.

    Example 1:

    Given 1->2->3->4, reorder it to 1->4->2->3.

    Example 2:

    Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    """ 步骤:
    1.小于等于2个节点直接返回
    2.找到中间节点(参考:876. Middle of the Linked List)
    3.中间节点后面的链表反转(参考:206. Reverse Linked List) 注意:记得断开中间节点后面的链表,不然链表会有环
    4.把反转后的链表插入前面的链表
    时间复杂度O(n), 空间复杂度O(1)
    """ class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head or not head.next or not head.next.next: return fast = head slow = head pre = ListNode(None) while fast and fast.next: slow = slow.next fast = fast.next.next mid = ListNode(None) tmp = slow slow = slow.next tmp.next = None mid.next = slow while slow.next: tmp = slow.next slow.next = slow.next.next tmp.next = mid.next mid.next = tmp cur = head mid = mid.next while mid: tmp = cur.next tmp1 = mid.next mid.next = cur.next cur.next = mid cur = tmp mid = tmp1
  • 相关阅读:
    CSS笔记(十)position属性与定位
    CSS笔记(九)轮廓
    前端需要学习算法吗 算法面的意义 职业规划
    Web前端笔试整理10
    Web前端笔试整理9
    Web前端笔试整理8
    Web前端笔试整理7
    Web前端笔试整理6
    JS 图片延迟加载/懒加载
    JS 同步与异步编程
  • 原文地址:https://www.cnblogs.com/boluo007/p/10334529.html
Copyright © 2011-2022 走看看