2019-05-19LeetCode234. 回文链表

使用快慢指针找到中间位置,再进行链表翻转,其实奇数的时候最后两个数组比较,有点巧妙 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,总之使用短的不为空

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。