Files
leetcode/234.palindrome-linked-list.java
2025-10-24 11:28:01 +08:00

55 lines
1.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* @lc app=leetcode id=234 lang=java
*
* [234] Palindrome Linked List
*/
// @lc code=start
/**
* 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 {
/**
* linked list求中点方案快慢指针
* 当fast移动n次时列表节点个数为1+2n或2n
* 此时slow移动n次时遍历节点个数为1+n
* 即节点总个数为奇数时slow刚好位于中点
* 当节点总个数为偶数时slow位于n+1节点即下半部分链表的开始节点
* @param head
* @return
*/
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head, prev = null, t;
while(fast != null && fast.next != null) {
fast = fast.next.next;
t = slow.next;
slow.next = prev;
prev = slow;
slow = t;
}
// 此时prev为上半部分开始节点cur为下半部分开始节点
// 如果fast不为空节点总数为奇数fast为空节点总数为偶数
if(fast != null) {
slow = slow.next;
}
boolean f = true;
while(slow != null) {
if(slow.val != prev.val) {
f = false;
}
slow = slow.next;
prev = prev.next;
}
return f;
}
}
// @lc code=end