LeetCode----Palindrome Linked List

Palindrome Linked List

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)空间内判断一个字符链表是否是回文的。因为需要O(1)空间,所以不能借助栈。

我的思路是:先得到整个链表的长度L,然后将链表分解成前L/2,和后L/2的链表,将后L/2的链表反转,然后比较这两个串。

Discuss中发现了更好的思路,可以用双指针遍历链表,其中一个指针遍历速度是另一个的两倍,这样避免了计算链表长度,同时也减少了运行时间。


代码:

# 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
        """
        l = self.getListLen(head)
        if l <= 1:
            return True
        index, mid = 0, l / 2
        p, pre, ppre = head, None, None
        while p:
            index += 1
            if index == mid + 1:
                ppre = pre
                ppre.next = None
                mid = p
                break
            pre = p
            p = p.next
        mid = self.reverseList(mid)
        # compare
        p1 = head
        p2 = mid
        while p1 and p2:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True

    def getListLen(self, head):
        p = head
        l = 0
        while p:
            l += 1
            p = p.next
        return l

    def reverseList(self, head):
        pre, cur = None, head
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre

你可能感兴趣的:(LeetCode,链表)