回文链表
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
示例 1:
输入:head = [1,2,2,1] 输出:true
示例 2:
输入:head = [1,2] 输出:false
提示:
- 链表中节点数目在范围
[1, 105]
内 0 <= Node.val <= 9
进阶:你能否用 O(n)
时间复杂度和 O(1)
空间复杂度解决此题?
如果随便做的话,大概率一下想到的是开个空间o(n)存一下然后想怎么判断怎么判断嘻嘻
回文链表,主要是无法直接像数组那样直接从中间去遍历,而看看进阶要求是让用o(n)时间复杂度和o(1)空间复杂度解决,那正好用刚才解决的逆序链表呗;逆序一半,然后分别从各自头开始比较,有不同就break,这样逆序一半的操作是【o(n),o(1)】,查找是循环一遍【o(n),o(1)】这样复杂度上是时间o(n),空间上o(1),正好满足。
# 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:
a = None
b = head
tmp = None
length_p = head
length = 0
reverse_times = 0
res_f = 0
if b == None or b.next == None:return True
# 计算出len
while length_p!=None:
length+=1
length_p = length_p.next
# reverse
while b!=None and reverse_times < length//2:
tmp = b.next
b.next = a
a = b
b = tmp
reverse_times+=1
if length % 2 == 1:
# ji shu
b = b.next
while a != None:
if a.val != b.val:
res_f = 1
break
a = a.next
b = b.next
if res_f == 1:return False
else:return True