回文链表
题目
![image-20240426221313798](https://img-blog.csdnimg.cn/img_convert/09a416c30ff9c4533c6016c83eef62c0.png)
![image-20240426221306372](https://img-blog.csdnimg.cn/img_convert/feae5bcab11334781864ad41e993694a.png)
解题思路
- 回文是指对称相等,例如"abba"属于回文,回文长度一定是偶数的
- 链表不具有随机访问的属性,因此不可能通过不断调整指针实现
- 观察回文特性,可以发现回文链表对称相等
- 在链表中间截断,分为俩个相等链表s1,s2
- 将s2反转,依次判断元素是否相等即可
- 判断结果后,要将链表还原,否则结果会出现问题
- 时间复杂度O(n),空间复杂度O(1)
具体代码
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
ListNode firstHalfEnd = endOfFirstHalf(head);
ListNode secondHalfStart = reverseList(firstHalfEnd.next);
ListNode p1 = head;
ListNode p2 = secondHalfStart;
boolean result = true;
while (result && p2 != null) {
if (p1.val != p2.val) {
result = false;
}
p1 = p1.next;
p2 = p2.next;
}
firstHalfEnd.next = reverseList(secondHalfStart);
return result;
}
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
private ListNode endOfFirstHalf(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}