PalindromeLinkedList

Source: Internet
Author: User
Keywords Fast pointer PalindromeLinkedList
Tags class list ps return

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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.