zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):143-Reorder List

    题目来源:

      https://leetcode.com/problems/reorder-list/


    题意分析:

      给定一个链表L:L0→L1→…→Ln-1→Ln,改变链表的排序为: L0→LnL1→Ln-1→L2→Ln-2→…,要求时间复杂度为O(n),不能改变节点的值。


    题目思路:

      题目思路是把链表拆成两个长度相等的链表,然后将后面的链表翻转,重新连起来。


    代码(python):

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def reorderList(self, head):
     9         """
    10         :type head: ListNode
    11         :rtype: void Do not return anything, modify head in-place instead.
    12         """
    13         if head == None or head.next == None or head.next.next == None:
    14             return
    15         slow = fast = head
    16         while fast and fast.next:
    17             slow = slow.next
    18             fast = fast.next.next
    19         head1,head2 = head,slow.next
    20         slow.next = None
    21         
    22         tmp = ListNode(0)
    23         tmp.next,p = head2,head2.next
    24         head2.next = None
    25         while p:
    26             tmp1,p = p,p.next
    27             tmp1.next = tmp.next
    28             tmp.next = tmp1
    29         head2 = tmp.next
    30         
    31         while head2:
    32             tmp2,tmp3 = head1.next,head2.next
    33             head1.next = head2
    34             head2.next = tmp2
    35             head1,head2 = tmp2,tmp3
    View Code
  • 相关阅读:
    Jmeter -- HTTP Request Defaults
    Jmeter -- 属性和变量
    Jmeter -- 逻辑控制器(Logic Controller)
    Jmeter报告优化之New XSL stylesheet
    Jmeter调试工具---HTTP Mirror Server
    Jmeter ----Bean shell使用
    转jmeter --JDBC请求
    Memcached 教程
    基于ZooKeeper的分布式Session实现
    Kafka配置说明
  • 原文地址:https://www.cnblogs.com/chruny/p/5474653.html
Copyright © 2011-2022 走看看