leetcode之判断一个链表是否是回文

用到列表反转与快慢指针,价值比较高:
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None:
            return True
        fast=slow=head
        while fast!=None and fast.next!=None:
            fast=fast.next.next
            slow=slow.next
        cur=slow
        prev=None
        while slow!=None:
            cur=slow
            slow=slow.next
            cur.next=prev
            prev=cur
        while cur:
            if cur.val!=head.val:
                return False
            cur=cur.next
            head=head.next
        return True
       

猜你喜欢

转载自blog.csdn.net/hai008007/article/details/80191844
今日推荐