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
       

你可能感兴趣的:(数据结构与算法)