判斷鏈表是否爲迴文結構*(Java實現)

鏈表的迴文結構,比如

1    2     2    1

再比如

上海自來水來自海上

狗日樓主在主樓日狗

也是迴文結構

那麼如何判斷鏈表是否是迴文結構?思路是這樣的:

1.先找到鏈表的中間結點
2.中間節點往後 對後面的結點進行逆置
3.對比前後兩個鏈表的內容是不是完全一樣

代碼實現:

public boolean chkPalindrome(ListNode head) {
        //考慮特殊情況
        if (head == null || head.next == null) {
            return true;
        }
        //1.先找到鏈表的中間結點
        int len = size(head);
        int steps = len / 2;
        ListNode newHead = head;
        for (int i = 0; i < steps; i++) {
            newHead = newHead.next;
        }
        //循環結束之後 newHead 已經指向中間節點
        //2.中間節點往後 對後面的結點進行逆置
        ListNode prev = null;
        ListNode cur = newHead;
        while (cur != null) {
            ListNode next = cur.next;
            if (next == null) {
                //使用 newHead 指向新鏈表的頭部
                newHead.next = cur;
            }
            cur.next = prev;
            prev = cur;
            cur = next;
        }

        //3.對比前後兩個鏈表的內容是不是完全一樣
        while (newHead != null) {
            if (head.val != newHead.val) {
                return false;
            }
            head = head.next;
            newHead = newHead.next;
        }
        return true;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章