Leetcode 234 Palindrome Linked List
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?
O(n)空间:存成数组后比较
class Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): temp = [] while head: temp.append(head.val) head = head.next return temp == temp[::-1]
O(1) 空间: 倒置后半段后比较
def is_palindrome(head) return true if not head or not head.next slow, fast = head, head while fast and fast.next fast = fast.next.next slow = slow.next end head2 = reverse(slow) while head2 if head.val != head2.val return false else head, head2 = head.next, head2.next end end return true end def reverse(head) return if not head a = head.next head.next = nil while a b = a.next a.next = head head = a a = b end head end