【leetcode】剑指 Offer II 027. 回文链表(python)

【leetcode】剑指 Offer II 027. 回文链表(python),第1张

方法一:借助数组,空间复杂度O(n)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        nums = []
        p = head
        while p:
            nums.append(p.val)
            p = p.next
        n = len(nums)
        for i in range(n//2):
            if nums[i] != nums[n - i - 1]:
                return False 
        return True
方法二:空间复杂度O(1)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        # 空间复杂度为O(1)解法:
        # 1.用快慢指针找到中间位置,
        # 2.将后半部分翻转链表(若为奇数个结点,则将中间结点算为前半部分)
        # 3.双指针p1,p2,遍历
        if not head or not head.next:
            return True

        # 1.用快慢指针找到中间位置
        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next

        # 2.迭代翻转后半部分链表,若为奇数个结点,则将中间结点算为前半部分
        pre = slow.next
        cur = pre.next
        pre.next = None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp

        p1 = head  # 3.双指针p1,p2,遍历
        p2 = pre
        while p1 and p2:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/798171.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存