Q:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
链接:https://leetcode-cn.com/problems/palindrome-linked-list/description/
思路:遍历链表,判断遍历结果是否是回文串
代码:
# 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 not head:
return True
tmp = []
pre = head
while pre.next:
tmp.append(pre.val)
pre = pre.next
tmp.append(pre.val)
return tmp == tmp[::-1]

本文介绍了一种判断链表是否为回文的方法,通过遍历链表并将节点值存入数组,再比较数组与其反转后的相等性来判断。提供了一个Python实现示例。
688

被折叠的 条评论
为什么被折叠?



