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
  • 相关阅读:
    SharePoint中获取当前登录的用户名
    SharePoint 2013 图文开发系列之InfoPath入门
    在InfoPath中如何获取当前用户的信息(Profile)
    更新当前列并添加其他列
    poj3067 Japan
    poj2481 Cows
    poj1195 Mobile phones
    poj2299 Ultra-QuickSort
    lower_bound()和upper_bound
    hdu4339 Query
  • 原文地址:https://www.cnblogs.com/boluo007/p/10334529.html
Copyright © 2011-2022 走看看