leetcode 每日签到 234. 回文链表
题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
思路
用栈思路,与匹配字符串相似
代码
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
a=[]
num=0
Head=head
while Head:
num+=1
Head=Head.next
if num==2:
return False if head.val!=head.next.val else True
for i in range(num//2):
a.append(head.val)
head=head.next
if num % 2 != 0:
head = head.next
for i in range(len(a)):
if a.pop()==head.val:
head=head.next
continue
else:
return False
return True

浙公网安备 33010602011771号