请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
解题思路:
1.使用快慢指针找到链表的中间节点
2.将链表的后半部分逆制
3.依次比较链表的前半部分和后半部分
class Solution:
def reverse(self,head):
if not head or not head.next:
return head
re=self.reverse(head.next)
head.next.next=head
head.next=None
return re
def isPalindrome(self, head: ListNode) -> bool:
if not head:
return True
f=l=head
while f and f.next:
f=f.next.next
l=l.next
h2=self.reverse(l)
while head and h2:
if head.val!=h2.val:
return False
head,h2=head.next,h2.next
return True
方法二:
将一半元素入栈,剩下元素与出栈元素一一对比