- 链表的回文结构:对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构
public boolean chkPalindrome(ListNode A) {
if(A == null){
return false;
}
if(A != null && A.next == null){
return true;
}
ListNode fast = A;
ListNode slow = A;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
ListNode prev = slow;
ListNode cur = slow.next;
while(cur != null){
ListNode curnext = cur.next;
cur.next = prev;
prev = cur;
cur = curnext;
}
ListNode q = prev;
while(A != slow){
if(A.val != q.val){
return false;
}
else{
if(A.next == q){
return true;
}
A = A.next;
q = q.next;
}
}
return true;
}
|