Palindrome Linked List
Description:
Implement a function to check if a linked list is a palindrome.
Example
Given 1->2->1, return true
Challenge
Could you do it in O(n) time and O(1) space?
Code:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: A ListNode.
@return: A boolean.
"""
def reverse(self, head):
nH = None
while head:
tmp = head
head = head.next
tmp.next = nH
nH = tmp
return nH
def isPalindrome(self, head):
# write your code here
if not head or not head.next:
return True
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
head2 = self.reverse(slow)
while head and head2:
if head.val!=head2.val:
return False
else:
head = head.next
head2 = head2.next
return True