题目
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
理解
先找到链表的中间结点,在将中间结点开始的后面所有结点逆置,然后比较两个链表的值,如果遇到不相等的直接返回false。如果相等,就一直两个引用往后走。
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class PalindromeList {
public boolean chkPalindrome(ListNode A) {
// write code here
ListNode mid=midNode(A);
ListNode h2=reverse(mid);
ListNode n1=A;
ListNode n2=h2;
while(n1!=null&&n2!=null){
if(n1.val!=n2.val)
return false;
n1=n1.next;
n2=n2.next;
}
return true;
}
public ListNode midNode(ListNode head){//找中间结点
ListNode pre=head;
ListNode cur=head;
while(cur!=null){
cur=cur.next;
if(cur==null)
break;
cur=cur.next;
pre=pre.next;
}
return pre;
}
public ListNode reverse(ListNode head){//逆置中间结点后面的链表
ListNode cur=head;
ListNode result=null;
while(cur!=null){
ListNode next=cur.next;
cur.next=result;
result=cur;
cur=next;
}
return result;
}
}