public class PalindromeList {
public boolean chkPalindrome(ListNode head) {
if (head == null) return true;
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null){
fast = head.next.next;
slow = head.next;
}
//slow走到了中间位置,依次把slow后面的数反转
ListNode cur = slow.next;
while (cur != null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//反转完成,回文(head.val==slow.val)
while (head != slow){
if (head.val != slow.val){
return false;
}
if (head.next == slow){ //偶数情况
return true;
}
head = head.next; //奇数情况
slow = slow.next;
}
return true;
}
}
Java:给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。
最新推荐文章于 2023-03-18 18:05:05 发布