leetcode 用fast-slow 指针的方法判断链表是否为回文链表。

题目:

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

思路:找到链表的中点,并从中间切断链表,将后半部分的链表翻转,最后再依次比较。

Python 实现

class Solution(object):
    def isPalindrome(self, head):
        if not head or not head.next:
            return True
        slow = head 
        fast = head
        p_last = head
        while fast and fast.next:
            p_last = slow
            slow = slow.next
            fast = fast.next.next
        #(1) 找到链表中点
        if not fast:      #如果跳出循环的时候fast 是None,则代表链表的结点数量为偶数,可以slow就是后半部分的head
            head2 = slow
            p_last.next = None
        else:	          #否则,链表结点总数为奇数,slow.next是后半部分的head
            head2 = slow.next
            p_last.next = None
        head2 = self.reverse(head2)  #(2)翻转链表
        
        return self.isEqual(head,head2) #(3)比较切断之后两个链表是否相同。
        
        
        
    def reverse(self,head):           #(2)翻转链表
        if not head or not head.next:
            return head
        p_next = None
        while head:
            p = head
            head = head.next
            p.next = p_next
            p_next = p
        return p_next
        
    def isEqual(self,head1,head2):    #(3)比较切断之后两个链表是否相同。
        while head1:
            if head1.val!=head2.val:
                return False
            head1 = head1.next
            head2 = head2.next
        return True


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值