题目描述
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
package Chapter2;
public class Palindrome {
// 题目描述
// 请编写一个函数,检查链表是否为回文。
// 给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
// 测试样例:
// {1,2,3,2,1}
// 返回:true
// {1,2,3,2,3}
// 返回:false
public boolean isPalindrome(ListNode pHead) {
if(pHead == null){
return true;
}
int length=0;
ListNode pHead1=pHead;
while(pHead1 != null){
length++;
pHead1=pHead1.next;
}
if(length == 1){
return true;
}
ListNode pHead2=pHead;
ListNode pHeadBeforeBegin=null;
ListNode pHeadBeforeEnd=null;
for(int i=0;i<length/2;i++){
if(pHeadBeforeBegin == null){
pHeadBeforeBegin=new ListNode(pHead2.val);
pHeadBeforeEnd=pHeadBeforeBegin;
}else{
ListNode tmp=new ListNode(pHead2.val);
pHeadBeforeEnd.next=tmp;
pHeadBeforeEnd=pHeadBeforeEnd.next;
}
pHead2=pHead2.next;
}
if(length%2 == 1){
pHead2=pHead2.next;
}
ListNode newBegin=new ListNode(-1);
ListNode newEnd=null;
while(pHead2 != null){
ListNode tmp=new ListNode(pHead2.val);
tmp.next=newEnd;
newEnd=tmp;
newBegin.next=tmp;
pHead2=pHead2.next;
}
newBegin=newBegin.next;
while(newBegin != null){
if(newBegin.val != pHeadBeforeBegin.val){
return false;
}
newBegin=newBegin.next;
pHeadBeforeBegin=pHeadBeforeBegin.next;
}
return true;
// write code here
}
public static void main(String[] args){
ListNode myListNode=ListNodeOperation.createListNode();
System.out.println(new Palindrome().isPalindrome(myListNode));
}
}
以下思路非常不错,具体代码就不贴了
image.png