13.回文链表
问题:
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
解决:
思想:
将数据存到一个list中,然后前后递进,进行判断
python代码:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Palindrome:
def isPalindrome(self, pHead):
# write code here
c=[]
while(pHead!=None):
c.append(pHead.val)
pHead=pHead.next
j=0
n=len(c)
while(j<(n/2-1)):
if(c[j]==c[n-1-j]):
j+=1
else:
return False
return True

289

被折叠的 条评论
为什么被折叠?



