【LeetCode】143. Reorder List 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/reorder-list/description/

题目描述:

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.

题目大意

把一个链表的前半部分正序,后半部分逆序,然后一个一个的连接起来。

解题方法

就像题目大意里面说的,需要三步。其实这个题对链表的考察非常的巧妙和详细了,可以说是三个题目了。

代码有点长,就是按照三步来写的。题目要求不能返回新节点,这个也提高了难度。

参考了:[leetcode]Reorder List @ Python

# 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: void Do not return anything, modify head in-place instead.
"""
if head and head.next and head.next.next:
#find mid
fast, slow = head, head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.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
while p:
temp = p
p = p.next
temp.next = dummy.next
dummy.next = temp
head2 = dummy.next # merge two linked list head1 and head2
p1 = head1
p2 = head2
while p2:
temp1 = p1.next
temp2 = p2.next
p1.next = p2
p2.next = temp1
p1 = temp1
p2 = temp2

日期

2018 年 6 月 25 日 ———— 新的一周,不要再想烦心事了。

最新文章

  1. Windows下使用Dev-C++开发基于pthread.h的多线程程序
  2. Kooboo CMS 之TextContent详解
  3. 修饰者模式(装饰者模式,Decoration)
  4. 《算法导论》习题解答 Chapter 22.1-7(关联矩阵的性质)
  5. iOS数据持久化(三)
  6. Javascript通过className选择元素
  7. iOS开源项目推荐|下拉刷新
  8. 关于SQL server的一些知识点
  9. (C)单链表
  10. Android While 循环导致的资源占用过高进而导致程序崩溃问题
  11. Android 退出多Activity的application的方式
  12. 分布式进阶(一)Windows 7下硬盘安装Ubuntu 14.04图文教程
  13. FFMPEG类库打开流媒体的方法(需要传参数的时候)
  14. Get Docker CE for CentOS
  15. EL和 JSTL? 在JSP中简化 java代码的写法!
  16. Config Server高可用
  17. maven向本地仓库导入jar包
  18. 在Windows2008下安装SQL Server 2005无法启动服务的解决办法
  19. Hackergame 2018的一道题目confused_flxg失败心得体会
  20. hdu3308

热门文章

  1. jQuery ajax常用示例
  2. 日常Java(测试 (二柱)修改版)2021/9/22
  3. Redis | 第11章 服务器的复制《Redis设计与实现》
  4. 零基础学习java------day6----数组
  5. Vue框架,computed和watch的区别
  6. 在 windows 系统上 安装与配置 PHP + Apache
  7. APK 反编译以及遇到的问题
  8. Linux学习 - 流程控制
  9. GO 定时器NewTimer、NewTicker使用
  10. zabbix之主动模式和proxy的主动模式