题目:
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?
思路:找到链表的中点,并从中间切断链表,将后半部分的链表翻转,最后再依次比较。
Python 实现
class Solution(object):
def isPalindrome(self, head):
if not head or not head.next:
return True
slow = head
fast = head
p_last = head
while fast and fast.next:
p_last = slow
slow = slow.next
fast = fast.next.next
#(1) 找到链表中点
if not fast: #如果跳出循环的时候fast 是None,则代表链表的结点数量为偶数,可以slow就是后半部分的head
head2 = slow
p_last.next = None
else: #否则,链表结点总数为奇数,slow.next是后半部分的head
head2 = slow.next
p_last.next = None
head2 = self.reverse(head2) #(2)翻转链表
return self.isEqual(head,head2) #(3)比较切断之后两个链表是否相同。
def reverse(self,head): #(2)翻转链表
if not head or not head.next:
return head
p_next = None
while head:
p = head
head = head.next
p.next = p_next
p_next = p
return p_next
def isEqual(self,head1,head2): #(3)比较切断之后两个链表是否相同。
while head1:
if head1.val!=head2.val:
return False
head1 = head1.next
head2 = head2.next
return True