回文的意思是翻转后和原来的内容相同,例如1-0-2-0-1就是回文。因此判断一个链表是否为回文,就可以将链表反转,比较两者是否相同即可。
但是考虑到反转后,我们只需要比较一般的内容是否相等就可以判断这个链表是否为回文链表,因此不需要比较全部的链表长度。
反转前部分链表可以通过Stack来实现。
假设不知道链表的长度,我们可以设置两个指针,fast和slow,fast每次走两步,slow每次走一步,因此当fast为null的时候,slow就是中间节点。
注意链表长度为基数和偶数的处理方式不同:
当链表长度为奇数时,中间链表节点需要跳过,不做入栈处理。
具体的代码如下:
import java.util.*;
class Node{
int data;
Node next;
public Node(int data){
this.data=data;
}
public Node(){}
}
public class Main{
public static void main(String[] args){
Node n1=new Node(5);
Node n2=new Node(0);
Node n3=new Node(8);
Node n4=new Node(8);
Node n5=new Node(0);
Node n6=new Node(5);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=n6;
n6.next=null;
System.out.println(isPalindrome(n1));
}
public static boolean isPalindrome(Node head){
if(head==null||head.next==null)
return false;
Node fast=head;
Node slow=head;
Stack<Integer> stack=new Stack<Integer>();
while(fast!=null&&fast.next!=null){
stack.push(slow.data);
slow=slow.next;
fast=fast.next.next;
}
if(fast!=null)
slow=slow.next;
while(slow!=null){
int value=stack.pop().intValue();
if(slow.data!=value)return false;
slow=slow.next;
}
return true;
}
}