描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1返回:true
思路:分奇数和偶数个节点,使用快慢指针,先找到中间节点,然后将后半节点逆序,如果是奇数节点只需判断头节点和慢指针是否相同,如果是偶数节点加一个if条件判断,头指针的下一个是不是慢指针。
public class PalindromeList {
public boolean chkPalindrome(ListNode head) {
// write code here
if (head == null) {
return true;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode cur = slow.next;
//slow.next = null;
while (cur != null) {
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
while (slow != head) {
if (slow.val != head.val) {
return false;
}
if (head.next == slow) {
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}
}