题目描述
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
翻转比较
先遍历一遍翻转存到新的链表中,再遍历一遍比较即可 时间复杂度o(n),空间复杂度o(n)
public boolean isPalindrome(ListNode pHead) {
// write code here
ListNode p=pHead;
ListNode res=null;
while (p!=null){
ListNode tem=new ListNode(p.val);
tem.next=res;
res=tem;
p=p.next;
}
while(pHead!=null){
if (pHead.val!=res.val){
return false;
}
pHead=pHead.next;
res=res.next;
}
return true;
}