1. 程式人生 > 其它 >CAD字型亂碼怎麼解決?CAD字型亂碼解決方法

CAD字型亂碼怎麼解決?CAD字型亂碼解決方法

給你一個單鏈表的頭節點 head ,請你判斷該連結串列是否為迴文連結串列。如果是,返回 true ;否則,返回 false 。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/palindrome-linked-list
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。


class Solution {

    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;
    }

    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;
    }


    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }

        ListNode mid = findMid(head);
        ListNode next = mid.next;

        ListNode reversedHead = reverse(next);

        ListNode p1 = head, p2 = reversedHead;

        boolean ret = true;

        while (p1 != null && p2 != null) {
            if (p1.val != p2.val) {
                ret = false;
                break;
            }
            p1 = p1.next;
            p2 = p2.next;
        }

        mid.next = reverse(reversedHead);

        return ret;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
心之所向,素履以往 生如逆旅,一葦以航