美文网首页
2019-05-19LeetCode234. 回文链表

2019-05-19LeetCode234. 回文链表

作者: mztkenan | 来源:发表于2019-05-19 22:02 被阅读0次

    使用快慢指针找到中间位置,再进行链表翻转,其实奇数的时候最后两个数组比较,有点巧妙 20min

    class Solution:
        def isPalindrome(self, head: ListNode) -> bool:
            slow,fast=head,head
            while(fast!=None and fast.next!=None): #偶数fast=None,slow=mid+1,奇数fast=end,slow=mid
                slow=slow.next
                fast=fast.next.next
            
            new=self.reverseList(slow)
            while(new!=None):  #如果偶数,两边相等,奇数,最后一个都是head
                if head.val!=new.val:return False
                head=head.next
                new=new.next
            return True
                
            
            
        def reverseList(self, head: ListNode) -> ListNode:
            if head==None or head.next==None:return head
            end=head.next
            h=self.reverseList(head.next)
            end.next=head
            head.next=None
            return h  
    

    另外两种考虑
    1.前部分的最后指针指向None,右部分最后一个不比较
    2.如果奇数,把slow=slow.next,总之使用短的不为空

    相关文章

      网友评论

          本文标题:2019-05-19LeetCode234. 回文链表

          本文链接:https://www.haomeiwen.com/subject/dxkczqtx.html