1. 程式人生 > 其它 >面試題 02.06. 迴文連結串列

面試題 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;
    }
}

心之所向,素履以往 生如逆旅,一葦以航