微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

小黑腰酸背痛继续leetcode:剑指 Offer II 027. 回文链表

小黑做法

# 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:
        arr = []
        while head:
            arr.append(head.val)
            head = head.next
        if arr[::-1] == arr:
            return True
        else:
            return False

在这里插入图片描述

递归法

# 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:
        self.pre_node = head
        def res_check(node = head):
            if node:
                if not res_check(node.next):
                    return False
                if self.pre_node.val != node.val:
                    return False
                self.pre_node = self.pre_node.next
            return True
        return res_check()   

在这里插入图片描述

快慢指针法

# 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:
        def reserve(head):
            prevIoUs = None
            current = head
            while current:
                next_node = current.next
                current.next = prevIoUs
                prevIoUs = current
                current = next_node
            return prevIoUs
        # 初始化快慢结点
        slow = fast = head
        while fast and fast.next and fast.next.next:
            fast = fast.next.next
            slow = slow.next
        # slow到中点,翻转后面
        after_reverse = reserve(slow.next)
        # 判断两段是否相等
        after_head = after_reverse
        pre_head = head
        while after_head and pre_head:
            if after_head.val != pre_head.val:
                return False
            after_head = after_head.next
            pre_head = pre_head.next
        return True

在这里插入图片描述

小黑生活

在这里插入图片描述


在这里插入图片描述

原文地址:https://www.jb51.cc/wenti/3284685.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐