链表的回文结构
题目描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
解决思路:
-
拿到链表的头节点,先找到链表的中间节点
-
然后从中间节点开始反转链表的后半部分
-
从头和尾同时往中间走
-
特别判断一下长度为偶数的链表
Code:
public boolean chkPalindrome(ListNode A) {
// write code here
//如果链表为空那么不是回文
if (A == null) {
return false;
}
//如果只有一个节点那么就是回文
if (A.next == null) {
return true;
}
//找到中间节点slow
ListNode fast = A;
ListNode slow = A;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//从slow开始进行反转链表
ListNode cur = slow.next;
while (cur != null) {
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//从前往后,从后往前走,中间没return就说明都相等
while (slow != A) {
//不相等return false
if (slow.val != A.val) {
return false;
}
//判断偶数情况
if (A.next == slow) {
return true;
}
//slow往前走,A往后走
slow =slow.next;
A = A.next;
}
return true;
}