Palindrome Linked List 解答
2024-08-29 06:02:21
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
最新文章
- Mimikatz 使用Tips
- oracle ||,
- linux笔记五-------编辑器
- Flume practices and sqoop hive 2 oracle
- HDU 4045 Machine scheduling --第二类Strling数
- js判断是否为空火undefined是否给undefined加引号
- declare和typeset DEMO
- Android ViewTreeObserver简介
- Android 播放gif图片
- ecshop 后台添加 成本价 利润
- jest for elasticsearch
- 利用sqlalchemy读取数据库 和pandas的Dataframe对象 互相生成
- 简单的线程Thread使用
- 【IDEA&;&;Eclipse】2、从Eclipse转移到IntelliJ IDEA一点心得
- this和构造器的内存分析(***)
- 2018面向对象程序设计(Java)第4周学习指导及要求
- Oracle时间的加减
- 团体程序设计天梯赛 L1-011. A-B
- wait();notify();简单例子
- 剑指offer 面试66题
热门文章
- Java 高效 MVC &; REST 开发框架 JessMA v3.2.1 即将发布
- 读书笔记-HBase in Action-第二部分Advanced concepts-(2)Coprocessor
- sublime怎么实现函数之间的跳转
- Gunplot 命令大全
- C语言随记-1
- Hacker(22)----解除系统中的密码
- windows下删除服务的方法
- 第一篇文章-VS的Local DB数据库连接失败,创建实例失败的解决方案
- Oracle序列简单应用
- silverlight visifire控件图表制作——silverlight 后台方法画图