Question

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

Solution

这一题思路并不难。要满足follow-up的要求,我们用到了快慢指针。

1. 用快慢指针得到前后两半list,这里有个技巧是quick先判断有无next,slow再走。这样就保证slow永远指向后半部分的前一个结点

2. Reverse 后半部分的list。三指针方法

3. 比较前半链表和反转后的后半链表

思路虽不难,但是要做到bug-free还是有难度。关键在于对以上每个子问题都熟悉。

 # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return True
slow = head
quick = head
while quick.next is not None:
quick = quick.next
if quick.next is not None:
quick = quick.next
slow = slow.next
# Reverse sub list between slow.next and quick
cur = slow.next
slow.next = None
then = cur.next
cur.next = None
while then is not None:
tmp = then.next
then.next = cur
cur = then
then = tmp
second_head = cur
# Compare first sub list and second sub list
cur1 = head
cur2 = second_head
while cur1 is not None and cur2 is not None:
if cur1.val != cur2.val:
return False
cur1 = cur1.next
cur2 = cur2.next
return True

最新文章

  1. Mimikatz 使用Tips
  2. oracle ||,
  3. linux笔记五-------编辑器
  4. Flume practices and sqoop hive 2 oracle
  5. HDU 4045 Machine scheduling --第二类Strling数
  6. js判断是否为空火undefined是否给undefined加引号
  7. declare和typeset DEMO
  8. Android ViewTreeObserver简介
  9. Android 播放gif图片
  10. ecshop 后台添加 成本价 利润
  11. jest for elasticsearch
  12. 利用sqlalchemy读取数据库 和pandas的Dataframe对象 互相生成
  13. 简单的线程Thread使用
  14. 【IDEA&&Eclipse】2、从Eclipse转移到IntelliJ IDEA一点心得
  15. this和构造器的内存分析(***)
  16. 2018面向对象程序设计(Java)第4周学习指导及要求
  17. Oracle时间的加减
  18. 团体程序设计天梯赛 L1-011. A-B
  19. wait();notify();简单例子
  20. 剑指offer 面试66题

热门文章

  1. Java 高效 MVC & REST 开发框架 JessMA v3.2.1 即将发布
  2. 读书笔记-HBase in Action-第二部分Advanced concepts-(2)Coprocessor
  3. sublime怎么实现函数之间的跳转
  4. Gunplot 命令大全
  5. C语言随记-1
  6. Hacker(22)----解除系统中的密码
  7. windows下删除服务的方法
  8. 第一篇文章-VS的Local DB数据库连接失败,创建实例失败的解决方案
  9. Oracle序列简单应用
  10. silverlight visifire控件图表制作——silverlight 后台方法画图