链表-(判断回文链表)的算法

# -*- coding:utf-8 -*-

""" 
Author: leadingme
Mail:[email protected]
MyWebsite:leadingme.top
"""

# 回文链表
"""
    算法要求: 判断一个链表是否为回文链表
    示例1:
        输入: 1->2
        输出: false
    示例2:
        输入: 1->2->2->1
    输出:
        true
"""

class ListNode(object):

    def __init__(self, value):
        self.val = value
        self.next = None

class Solution(object):

    def isPalindrome(self, head: ListNode) -> bool:
        if head is None:   # 判断为空链表
            return True
        valList = []
        while head:   # 将每个节点的值逐一保存到列表中
            valList.append(head.val)
            head = head.next
        rList = valList[::-1] # 切片取逆
        if rList == valList:
            return True
        else:
            return False

发布了54 篇原创文章 · 获赞 24 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43388615/article/details/105306376