Problem: 234. 回文链表
思路
参考:
- https://leetcode.cn/problems/palindrome-linked-list/solutions/457059/hui-wen-lian-biao-by-leetcode-solution
解题方法
- 结合官方题解,列表一般有两种实现,即数组或链表,此处代码中的预定义以明确是采用链表实现。由于链表本身为读取带来一定困难,所以我们常常将链表内容复制入数组,再进行后续考虑;
- 熟悉 python中的数组实现,即列表list数据结构,其读取时间复杂度为 O ( 1 ) O(1) O(1);
- 学会从预定义内容中看明白链表的操作,对链表有所了解,明白节点的值与指针的概念,并学会如何访问节点的值与更新指针;
- 通过循环实现对链表内容到数组的复制;
- 结合python的特性,构建反转列表非常简单,即
nums[::-1]
,可以快速进行原数组与反转数组的比较,若两者相同,便是回文!
以下内容为 GPT 对 nums[::-1]
解释:
In Python, nums[::-1]
is a common way to create a reversed copy of a list. This slice notation is a powerful feature in Python for list manipulation. Let’s break it down:
-
nums
is your list. -
The
:
inside the square brackets is the slicing operator, and it’s used to select a portion of the list. -
The
-1
after the second colon specifies the step. In this context, it means we’re moving backward through the list, one element at a time.
So, nums[::-1]
starts from the end of the list and steps backward until it reaches the beginning, effectively creating a reversed copy of the list.
In the context of your code, return nums == nums[::-1]
is checking whether the list nums
is equal to its reversed version. This is a way to check if the list is a palindrome:
-
If
nums
is the same asnums[::-1]
, it means the list reads the same forwards and backwards, and the function will returnTrue
, indicating the list is a palindrome. -
If
nums
is different fromnums[::-1]
, the function will returnFalse
, indicating the list is not a palindrome.
复杂度
时间复杂度:
O ( n ) O(n) O(n)
空间复杂度:
O ( n ) O(n) O(n)
Code
# 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 = [] # 创建一个空数组/列表,用来先讲链表复制到数组中
curr = head # 创建 curr 指向 head
while curr is not None: # 如果指针不为空
nums.append(curr.val) # 将当前指针所指的 value 复制添加进入数组
curr = curr.next # 更新 curr 指针
# 直接比较原数组/列表和反转数组/列表
return nums == nums[::-1]