0
点赞
收藏
分享

微信扫一扫

LeetCode234_回文链表


1. 题目

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

示例 1:
输入: 1->2
输出: false

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

进阶:
你能否用 O(n) 时间复杂度和 O(1)

2. 题解

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None:
return True

res = []
cur = head
while cur:
res.append(cur.val)
cur = cur.next

left = 0
right = len(res) - 1
while left < right:
if res[left] == res[right]:
left += 1
right -= 1
else:
return False
return True


举报

相关推荐

0 条评论