链表的回文判断,因为限制了空间复杂度。所以不能采用建立一个列表去存储该链表。所以想到了将链表翻转,然后搜索到中间位置,对中间位置之后的链表进行翻转,然后对比即可。
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head == None or head.next == None:
return True
fast=slow=head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
slow = slow.next
slow = self.reverselist(slow)
while(slow):
if slow.val != head.val:
return False
else:
slow = slow.next
head = head.next
return True
def reverselist(self,head):
new_node = None
while(head):
p = head
head = head.next
p.next = new_node
new_node = p
return new_node