回文链表
https://leetcode-cn.com/problems/palindrome-linked-list/ (opens new window) 需要注意的点 第一种,遍历链表得到数组,复制数组的相反副本,比较数组的值 第二种,快慢指针
# 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: ListNode) -> bool:
if head is None:
return False
l = []
while head is not None:
l.append(head.val)
head = head.next
l1 = l[::-1]
return l1 == l
# 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: ListNode) -> bool:
slow = head
fast = head
# 推进快慢指针(节点)
# 快节点一次两步,慢节点一次一步
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
# 如果快节点不是Null,说明慢节点在中心点
if fast is not None:
slow = slow.next
left = head
right = self.reverseList(slow)
while right is not None:
if left.val != right.val:
return False
left = left.next
right = right.next
return True
'''
反转链表
'''
def reverseList(self, node: ListNode) -> ListNode:
pre = None
cur = node
while cur is not None:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre