https://leetcode-cn.com/problems/palindrome-linked-list/
需要注意的点
第一种,遍历链表得到数组,复制数组的相反副本,比较数组的值
第二种,快慢指针
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution:def isPalindrome(self, head: ListNode) -> bool:if head is None:return Falsel = []while head is not None:l.append(head.val)head = head.nextl1 = l[::-1]return l1 == l
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution:def isPalindrome(self, head: ListNode) -> bool:slow = headfast = head# 推进快慢指针(节点)# 快节点一次两步,慢节点一次一步while fast is not None and fast.next is not None:slow = slow.nextfast = fast.next.next# 如果快节点不是Null,说明慢节点在中心点if fast is not None:slow = slow.nextleft = headright = self.reverseList(slow)while right is not None:if left.val != right.val:return Falseleft = left.nextright = right.nextreturn True'''反转链表'''def reverseList(self, node: ListNode) -> ListNode:pre = Nonecur = nodewhile cur is not None:next = cur.nextcur.next = prepre = curcur = nextreturn pre
