zoukankan      html  css  js  c++  java
  • 力扣—Reorder List(重排链表)python实现

    题目描述:

    中文:

    给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
    将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.

    示例 2:

    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

    英文:

    Given a singly linked list L: L0→L1→…→Ln-1→Ln,
    reorder it to: L0→Ln→L1→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
    
    class Solution(object):
        def reorderList(self, head):
            """
            :type head: ListNode
            :rtype: None Do not return anything, modify head in-place instead.
            """
            if head == None or head.next == None or head.next.next == None:
                return head
            
            slow = fast =head
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next
            head1 = head
            head2 = slow.next
            slow.next = None
            
            dummy = ListNode(0)
            dummy.next = head2
            p = head2.next
            head2.next = None              
            while p:                                        
                tmp=p; p=p.next                            
                tmp.next=dummy.next
                dummy.next=tmp
            head2=dummy.next
            
            p1 = head1; p2 = head2
            while p2:
                tmp1 = p1.next; tmp2 = p2.next
                p1.next = p2; p2.next = tmp1
                p1 = tmp1; p2 = tmp2

    题目来源:力扣

  • 相关阅读:
    MySQL数据库的优化
    PHP中获取文件扩展名
    PHP实现几种经典算法详解
    Linux服务器上crontab定时执行脚本文件
    LeetCode每日一题(五):加一
    巧妙利用枚举找出数组元素所在区间
    PHP实现几种经典算法详解
    _initialize() 区别 __construct()
    LeetCode每日一题(四):搜索插入位置
    LeetCode每日一题(三):移除元素
  • 原文地址:https://www.cnblogs.com/spp666/p/11673379.html
Copyright © 2011-2022 走看看