题意: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?
思路:一般来说判断回文肯定不会用链表来判断的,太麻烦了。。这题的目的还是用来熟悉链表的操作,方法就是先将后一半链表反转,再以一定的间隔比较各位是否相等,比如s=’1,2,3,2,1’,将后一部分反转为’1,2,1,2,3’,再将两个指针分别从第一个1和第二个2开始向后遍历即可,这里有一个技巧,一般要求链表长度时用到的方法都是遍历整个串,求出链表长度除以2,再一位位的移到该结点,现在有一个空间换时间的方法就是多申请一个指针,每次跨2步,这样,当他到达末尾时,每次跨一步的指针就正好到达链表中间,附代码:
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
h = ListNode(0)
h.next = head
fast, slow = h, h
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
slow.next = self.reversedlist(slow.next)
p, q = h.next, slow.next
while p!=slow.next:
if q.val == p.val:
p, q = p.next, q.next
else:
return False
return True
def reversedlist(self, head):
pre = None
while head:
cur = head
head = head.next
cur.next = pre
pre = cur
return pre