【力扣100】234.回文链表

添加链接描述

# 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:
        # 思路是用一个数组接收这些值,然后数组前半部分反转,跟后半部分对比
        nums=[]
        while head:
            nums.append(head.val)
            head=head.next
        reversed_nums=list(reversed(nums))
        # print(nums)
        # print(reversed_nums)
        if reversed_nums==nums:
            return True
        return False

需要注意的是:

  1. reversed()函数返回的是一个反向迭代器,如果想把它变成链表需要使用list()函数
  2. 如果想访问反向迭代器里面的元素,需要print(x for x in reversed(nums))


如何找到一个链表的中间节点?

  1. 使用快慢指针
  2. 快指针一次走两步,慢指针一次走一步
  3. while fast.next is not None and fast.next.next is not None这个是判断条件,当快指针走完的时候,慢指针走向中间节点

你可能感兴趣的:(leetcode,链表,算法)