Palindrome Linked List 解答
2015-11-03 07:49
176 查看
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
相关文章推荐
- 动手编写自己的级联下拉列表 - 基础
- Codevs 加密算法
- java JDBC编程——从属性文件读取信息,并创建到数据库的连接
- 模拟赛记录(3):11.02 论想题思路
- 创业感悟:低调务实是创业者最可贵的精神
- 日期选择器控件学习
- 人生应该勇往直前,不能患得患失
- java IO编程——复制一个文件中的内容到另一个文件
- codevs4247 奇特的生物
- java IO编程——显示一个目录的层次结构
- 模拟赛记录(2):10.31 T1 double精度问题,T2 Trie树
- VC++的一些常用方法的累积
- OSChina 周二乱弹 —— 程序猿的 BUG
- java网络编程——Socket和ServerSocket,套接字编程——简单聊天室改进
- Cocos Studio 2.3.2不再支持直接导入PSD文件
- 递归学习:N皇后 [暨接受六神指点后感]
- OI历程日常
- OI历程日常
- Linux文件系统
- Operating System: Three Easy Pieces --- Lock Concurrent Data Structures (Note)