剑指Offer II027.回文链表
给定一个链表的 头节点 head
,请判断其是否为回文链表。
如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
提示:
- 链表 L 的长度范围为
[1, 105]
0 <= node.val <= 9
思路:首先使用快慢指针找到链表的中间节点,需要注意链表的长度是奇数还是偶数。然后将后半个链表进行反转。反转后,分别遍历前半部分和后半部分,判断每个节点的值是否相同。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) {
return true;
}
ListNode slow = head, fast = head.next;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if(fast != null) {
slow = slow.next;
}
fast = slow;
slow = head;
fast = rev(fast);
while(slow != null && fast != null) {
if(slow.val != fast.val) {
return false;
}
slow = slow.next;
fast = fast.next;
}
return true;
}
public ListNode rev(ListNode head) {
ListNode pre = head, cur = head.next;
head.next = null;
while(cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}