面试题 02.06-1489. 回文链表
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
class Solution:
def isPalindrome(self, head) -> bool:
#先地板除取长度一半开始前后对应
length=len(head)
length1=length//2
n=0
for i in range(length1):
#因为列表中0指针代表第一个,-1代表倒数第一个所以m比i多1然后取负
m = i+1
if head[i]==head[-m]:
n=n+1
continue
else:
return 'wrong'
#检查是否全部具有回文属性
if n==length1:
return 'ture'
head=[1,2,3,4,2,1]
a=Solution()
a.isPalindrome(head)
**note:**由于初学者小白,这里不太懂leecode中链表在python里如何操作,回文就以列表的形式表达。
参考答案:
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
dp=[]
p=head
while p:
dp.append(p.val)
p=p.next
return dp==list(reversed(dp))
作者:tong-7
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci/solution/python-jian-dan-by-tong-7/
总结
在leecode中经常遇到链表操作,从参考答案中可知,在leecode后台,使用链表方式和其他语言应该一致,先实例化,后面加’.val’取当前值,’.next’指针指向下个位置,如需取值还是要加’.val’。