/**
* 功能:检查链表是否为回文
*/
三种方法:
1、反转链表,然后与原链表比较
//反转并比较
public static boolean isPalindrome(LinkedListNode head){
if( head== null)
return false;
LinkedListNode node= head; //将链表内容储存,防止反转时对head的修改
while( head. next!= null){
LinkedListNode reverseHead= reverse(head);//之后head.next指向空
if( node. data!= reverseHead. data){
return false;
} else{
node= node. next;
reverseHead. next= reverseHead;
}
}
return true;
}
public static LinkedListNode reverse(LinkedListNode head){
if( head== null|| head. next== null)
return head;
LinkedListNode reverseHead= reverse(head.next);
head. next. next= head;
head. next= null;
return reverseHead;
}
2、迭代法
//迭代法
/**
* 思路:将立案表前半部分反转,利用栈来实现
* 链表长度未知时:使用fast和slow迭代访问,将slow的数据入栈。当fast到达尾部时,slow到达中间。
* 每次比较时,将当前节点和栈顶元素作比较判断是否是回文序列。
* @param head
* @return
*/
public static boolean isPalindrome2(LinkedListNode head){
LinkedListNode fast= head;
LinkedListNode slow= head;
Stack<Integer> stack= new Stack<Integer>();
while( fast!= null&& fast. next!= null){
stack.push( slow. data);
fast= fast. next. next;
slow= slow. next;
}
//如果元素为奇数个,则跳过中间元素
if( fast!= null)
slow= slow. next;
while( slow!= null){
int top= stack.pop().intValue();
if( top!= slow. data)
return false;
slow= slow. next;
}
return true;
}
3、递归法
//递归法
public static boolean isPalindrome3(LinkedListNode head){
Result result= isPalindromeRecurse(head,listSize(head ));
return result. result;
}
public static Result isPalindromeRecurse(LinkedListNode head, int length){
if( length==0|| head== null)
return new Result( head. next, true);
if( length==1)
return new Result( head. next, true);
if( length==2)
return new Result(head. next. next, head. next. data== head. data);
Result res= isPalindromeRecurse(head.next,length-2);
if( res. node== null||! res. result){
return res;
} else{
res. result=( head. data== res. node. data);
res. node= res. node. next;
return res;
}
}
public static int listSize(LinkedListNode head){
int len=0;
while( head!= null){
len++;
head= head. next;
}
return len;
}
//静态方法调用内部类时,内部类要是静态的。
public static class Result{
public LinkedListNode node;
public boolean result;
public Result(){
}
public Result(LinkedListNode n, boolean res){
this. node= n;
this. result= res;
}
}