PalindromeLinkedList
Write by myself:
# Definition for singly-linked list. # Class ListNode (object): # def __init __ (self, x): # self.val = x # self.next = None class Solution (object): def isPalindrome nums = [] p = head while p! = None: nums.append (p.val) # added to list p = p.next temp = nums [: ": type head: ListNode: rtype: bool" : -1] # negate return temp == nums # Compare equality
In accordance with the ideas of others, write the code
# class # ListNode (object): # def __init __ (self, x): # self.val = x # self.next = None class Solution # utf-8 - * - # Definition for singly-linked list. (object): def isPalindrome (self, head): "" ": type head: ListNode: rtype: bool" "# Set the fast and slow pointers, slow pointers only one step at a time, When the pointer is finished, the # position of the slow pointer is the midpoint. slow: fast = head, head while fast.next! = None and fast.next.next! = None: slow = slow.next fast = fast.next.next # Reverse order the second half of the linked list p = slow .next slow.next = None while p: temp = p.next p.next = slow.next slow.next = pp = temp The value of #ph is head, and the value of ps is slow.next # even number of nodes, odd number Node, slow will stop at the previous node to be compared ph, ps = head, slow.next while ph and ps: if ps.val! = Ph.val: return False ph = ph.next ps = ps.next return True