请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
ListNode的定义代码:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
代码1:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
@author: WowlNAN
@github: https://github.com/WowlNAN
@blog: https://blog.csdn.net/qq_21264377
"""
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
a=[]
temp=head
while temp!=None:
a.append(temp.val)
temp=temp.next
l=len(a)
if l==1:
return True
mid=int(l/2)
for i in range(mid):
if a[i]!=a[l-1-i]:
return False
return True
代码2:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
@author: WowlNAN
@github: https://github.com/WowlNAN
@blog: https://blog.csdn.net/qq_21264377
"""
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head==None:
return True
temp=head
i=0
while temp!=None:
i+=1
temp=temp.next
l=i
mid=int(l/2)
temp=head
i=0
flag=l%2==0
left=''
right=''
while temp!=None:
if i<mid:
left+=str(temp.val)
elif i==mid:
if flag:
right=str(temp.val)+right
else:
right=str(temp.val)+right
i+=1
temp=temp.next
return left==right
这里O(1)空间复杂度是?
如果是指单个链表指针的空间的常数,两段代码似乎都不符合要求。
那么试试代码3:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
@author: WowlNAN
@github: https://github.com/WowlNAN
@blog: https://blog.csdn.net/qq_21264377
"""
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head==None:
return True
left=head
i=0
while left!=None:
i+=1
left=left.next
l=i
mid=int(l/2)
i=0
left=head
right=head
while right!=None:
if i==mid:
break
right=right.next
i+=1
pre=None
cur=right
nex=None
rightHead=None
while cur!=None:
nex=cur.next
if nex==None:
rightHead=cur
cur.next=pre
pre=cur
cur=nex
right=rightHead
i=0
while left!=None and right!=None and i<mid:
if left.val!=right.val:
return False
left=left.next
right=right.next
i+=1
return True
原理简单就不说了。时间复杂度 实际应该是3遍遍历链表,即O(n),空间也满足O(1)。
注:最后一个循环i的存在只是为了比较清晰说明循环的终止位置或者说是循环次数,即 n / 2。
参考资料: