面试题 02.06. 回文链表
编写一个函数,检查输入的链表是否是回文的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private ListNode reverse(ListNode head) {
ListNode cur = head, pre = null, next;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
private ListNode findMid(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return head;
}
ListNode slow = head.next;
ListNode fast = head.next.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
ListNode mid = findMid(head);
ListNode tail = reverse(mid.next);
ListNode p1 = head, p2 = tail;
boolean ok = true;
while (p1 != null && p2 != null) {
if (p1.val != p2.val) {
ok = false;
break;
}
p1 = p1.next;
p2 = p2.next;
}
mid.next = reverse(tail);
return ok;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}