题目来源
题目描述
解答一
将值复制到数组之后用双指针法(使用集合List存储链表中的元素,然后双指针,一个从头开始,一个从结尾开始进行比较)
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list=new ArrayList<>();
ListNode cur=head;
while(cur!=null){
list.add(cur.val);
cur=cur.next;
}
int i=0;
int j=list.size()-1;
while(i<j){
if(!list.get(i).equals(list.get(j))){
return false;
}
i++;
j--;
}
return true;
}
}
解答二(递归)
class Solution {
private ListNode frontPointer;
public boolean isPalindrome(ListNode head) {
frontPointer=head;
return recuriselyCheck(head);
}
private boolean recuriselyCheck(ListNode currentNode){
if(currentNode!=null){
if(!recuriselyCheck(currentNode.next)){
return false;
}
if(currentNode.val!=frontPointer.val){
return false;
}
frontPointer=frontPointer.next;
}
return true;
}
}
解答三:快慢指针
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null){
return true;
}
ListNode first=endOfFirst(head);
ListNode second=revserse(first.next);
//判断是否为回文
ListNode p1=head;
ListNode p2=second;
boolean result=true;
while(result&&p2!=null){
if(p1.val!=p2.val){
result=false;
}
p1=p1.next;
p2=p2.next;
}
first.next=revserse(second);
return result;
}
private ListNode revserse(ListNode head){
ListNode prev=null;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
}
private ListNode endOfFirst(ListNode head){
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}