• [leetcode]Reorder List @ Python


    原题地址:http://oj.leetcode.com/problems/reorder-list/

    题意:

    Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-2→…

    You must do this in-place without altering the nodes' values.

    For example,
    Given {1,2,3,4}, reorder it to {1,4,2,3}.

    解题思路:1,先将链表截断为两个相等长度的链表,如果链表长度为奇数,则第一条链表长度多1。如原链表为L={1,2,3,4,5},那么拆分结果为L1={1,2,3};L2={4,5}。拆分的技巧还是快慢指针的技巧。

           2,将第二条链表L2翻转,如将L2={4,5}翻转为L2={5,4}。

                  3,按照题意归并链表。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param head, a ListNode
        # @return nothing
        def reorderList(self, head):
            if head==None or head.next==None or head.next.next==None: return head
            
            # break linked list into two equal length
            slow = fast = head                              #快慢指针技巧
            while fast and fast.next:                       #需要熟练掌握
                slow = slow.next                            #链表操作中常用
                fast = fast.next.next
            head1 = head
            head2 = slow.next
            slow.next = None
    
            # reverse linked list head2
            dummy=ListNode(0); dummy.next=head2             #翻转前加一个头结点
            p=head2.next; head2.next=None                   #将p指向的节点一个一个插入到dummy后面
            while p:                                        #就完成了链表的翻转
                tmp=p; p=p.next                             #运行时注意去掉中文注释
                tmp.next=dummy.next
                dummy.next=tmp
            head2=dummy.next
    
            # merge two linked list head1 and head2
            p1 = head1; p2 = head2
            while p2:
                tmp1 = p1.next; tmp2 = p2.next
                p1.next = p2; p2.next = tmp1
                p1 = tmp1; p2 = tmp2
  • 相关阅读:
    图片上传 多张
    ES6的新特性
    css超出一行添加省略号属性:text-overflow和white-space
    JQuery 中 is(':visible') 解析及用法
    Git详解之Git分支
    jQuery选择器和选取方法
    git命令之git remote的用法
    运算符中的一些小技巧
    Git 忽略一些文件不加入版本控制
    git 查看远程分支、本地分支、创建分支、把分支推到远程repository、删除本地分支
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3700846.html
Copyright © 2020-2023  润新知