LeetCode 234. 回文链表 java
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
JAVA 代码:
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
ListNode prev = null;
while (fast != null && slow != null) {
fast = fast.next == null ? fast.next : fast.next.next;
slow = slow.next;
}
// reverse
while (slow != null) {
ListNode ovn = slow.next;
slow.next = prev;
prev = slow;
slow = ovn;
}
// check
while (head != null && prev != null) {
if (head.val != prev.val) {
return false;
}
head = head.next;
prev = prev.next;
}
return true;
}
}