0%

Leetcode 234 回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为 回文链表。如果是,返回 true ;否则,返回 false

用一个 nums 数组存起来链表的值,然后双指针判断是否是回文链表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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: Optional[ListNode]) -> bool:
nums = []
while head is not None:
nums.append(head.val)
head = head.next
n = len(nums)
if n == 1 or n == 0:
return True
i, j = 0, n-1
while i <= j:
if nums[i] == nums[j]:
i += 1
j -= 1
continue
else:
return False
return True