欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode[234] Palindrome Linked List

程序员文章站 2022-06-09 15:58:48
...

234. Palindrome Linked List

recursion not work, stack will be overflow

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
       
        def check(head):
            if not head:
                return True
            ret=check(head.next) & self.temp.val==head.val
            self.temp=self.temp.next
            return ret
            
            
        self.temp=head       
        return check(head)

using iterative way

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        #find the middle
        f=head
        s=head
        pre=s
        if not head or not head.next:
            return True
        while f and f.next:
            f=f.next.next
            s=s.next
        
        
        #reverse the latter half,now we find a middle node, it can be aabaa pattern or acca pattern, here is a trik, mark the middle.next=None,
        #b.next=None or c.next=None
        pre=None
        while s:
            t=s.next
            s.next=pre
            pre=s
            s=t
        while pre:
            if pre.val!=head.val:
                return False
            pre=pre.next
            head=head.next
        return True
相关标签: link list