【题目】
请判断一个链表是否为回文链表。
【示例 1】
输入: 1->2
输出: false
【示例 2】
输入: 1->2->2->1
输出: true
【进阶】
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
【代码】
【Python】
【方法1:普通法】
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
num=[]
while head:
num.append(head.val)
head=head.next
return num==num[::-1]
【方法2:进阶法】
空间复杂度:O(1)
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
cnt=0
t=head
while t:
cnt+=1
t=t.next
half1=head
pos=None
for i in range(cnt//2):
pos=head
head=head.next
pos.next=None
if cnt%2:
head=head.next
#对后半部分链表逆转
pre=head
cur=head.next
pre.next=None
while cur:
post=cur.next
cur.next=pre
pre=cur
cur=post
while pre and half1:
if pre.val!=half1.val:
return False
pre=pre.next
half1=half1.next
return True