Problem: 234. 回文链表
思路
遍历链表将所有的元素存入元素列表中,利用两个指针分别指向列表的开始位置和结束位置,不断移动两个指针,直到他们相遇。过程中一旦它们的值不相等,就代表该链表不是回文的。
复杂度
时间复杂度: 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:
ls = []
while head:
ls.append(head.val)
head = head.next
length = len(ls)
for i in range(len(ls) // 2):
if ls[i] != ls[length-1-i]:
return False
return True
1327

被折叠的 条评论
为什么被折叠?



