234 回文链表
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
输入:head = [1,2,2,1]
输出:true
输入:head = [1,2]
输出:false
首先把链表转换为数组,然后定义首尾指针,如果只针对应元素值不相等就直接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: Optional[ListNode]) -> bool:
cur = head
res = []
while cur != None:
res.append(cur.val)
cur = cur.next
left, right = 0, len(res)-1
while left < right:
if res[left] == res[right]:
left += 1
right -= 1
else:return False
return True