leetcode234. Palindrome Linked List

来源:互联网 发布:java aplication 编辑:程序博客网 时间:2024/05/05 16:47

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?

反转链表法,将链表后半段原地翻转,再将前半段、后半段依次比较,判断是否相等,时间复杂度O(n),空间复杂度为O(1)满足题目要求。

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def reverseList(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if head==None:            return None        p1=None        p2=head        while(p2):            tmp=p2.next            p2.next=p1            p1=p2            p2=tmp        return p1    def isPalindrome(self, head):        """        :type head: ListNode        :rtype: bool        """        if head==None or head.next==None:            return True        fast=head        slow=head        while(fast and fast.next):            slow=slow.next            fast=fast.next.next        if fast:            slow=self.reverseList(slow.next)        else:            slow=self.reverseList(slow)        while(slow):            if head.val!=slow.val:                return False            slow=slow.next            head=head.next        return True
0 0
原创粉丝点击