leetcode 234. 回文链表(Easy)(链表)

题目:

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

思路:

      判断一个链表是否为回文链表,起初想到的方法是翻转整张链表再与原本的链表做比较,可是这样一来空间复杂度是O(n),不合题意。要使得空间复杂度是O(1),就要在原本的链表上进行调整。回文链表是对称的,我们将链表的后半部分进行翻转,这样一来只需判断后半部分与链表前半部分的val值是否一致即可。那么怎么找到链表的中间位置呢?这就需要用到“快慢指针”的方法。两个指针同时指向头结点,快指针步长是慢指针步长的两倍。当快指针跨不出两步时停止,此时慢指针所指向节点的下一个节点就是链表需要翻转的开始位置。翻转完成后,将翻转完成后链表的后半部分与链表前半部分一个一个进行比较,只有当后半部分走完时返回True。

代码:

# 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 == None:
            return True
        if head.next == None:
            return True
        if head.next.next == None:
            if head.val == head.next.val:
                return True
            else:
                return False        
        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        mid = self.reverse(slow.next)
        while mid != None:
            if mid.val != head.val:
                return False
            head = head.next
            mid = mid.next
        return True
        
    def reverse(self,head):
        H = None
        cur = head
        nex = cur.next
        while nex !=None:
            cur.next = H
            H = cur
            cur = nex
            nex = nex.next
        cur.next = H
        return cur
    

猜你喜欢

转载自blog.csdn.net/weixin_40449071/article/details/82798855