Leetcode: Palindrome Linked List
2015-08-29 11:15
441 查看
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?
Show Tags
Show Similar Problems
Solution
[code]# 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==None or head.next==None: return True # segmentate list slow, fast = (head,)*2 while fast.next!=None and fast.next.next!=None: slow = slow.next fast = fast.next.next slow = slow.next head1,head2 = head,slow head2 = self.reverselist(head2) while head2!=None: if head1.val!=head2.val: return False head1, head2 = head1.next, head2.next return True def reverselist(self, head): if head==None or head.next==None: return head tail = head.next newhead = self.reverselist(tail) tail.next = head head.next = None return newhead
Error Path
if head==None or head.next==None: return head should return Truefor segmentate list, should add slow=slow.next for the case len(list)==2
相关文章推荐
- Linux新手入门:Unable to locate package错误解决办法
- 4.solrj对索引的增删改查
- Win10 Mobile/PC版《照片》更新以及下载:Bug修复和性能优化
- HDU 1071 The area(计算几何)
- Java中实现CallBack功能
- matlab常用小函数(一)
- NGUI_2.6.3_(3D视图&ScrollView)
- cc、gcc、g++、CC的区别概括
- NSString转NSData,以及char*转NSData
- 少一点伤感
- 瀑布流布局——jquery
- 2015.8.28 字符串
- HDU 2955 Robberies
- 别让任何人偷走您的梦
- Android:透明状态栏的效果实现
- SDUT-3303-来发背包开开胃
- Smart210 U-Boot移植 之Readme文件分析 (基于u-boot-2015.07)
- uvalive5989(水题)
- 网站实时信息采集和统计graphite
- iOS中ScrollView的属性和方法详解