描述:
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
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
if(A == null || A.next == null){
return true;
}
ListNode fast = A;
ListNode slow = A;
//1.寻找中置位
while(fast != null && fast.next != null){
fast = fast.next;
slow = slow.next;
if(fast.next != null){
fast = fast.next;
}
}
//此时slow在中置位 fast在最后一位
//2.逆置
ListNode cur = slow.next;
ListNode curNext = null;
while(cur != null){
curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//3.从两边同时判断
while(slow != A){
if(slow.val != A.val){
return false;
}
if(A.next == slow){
return true;
}
if(slow.val == A.val){
slow = slow.next;
A = A.next;
}
}
return true;
}
}