java迴文單鏈表

wrong了好多次就是過不了
過不了 畫圖板搞起!
成功AC
在這裏插入圖片描述
附代碼

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next ==null) {
            return true;
        }
        int size = 0;
        ListNode p = head;
        while (p != null) {
            p = p.next;
            size++;
        }
        
        ListNode pre = null;
        ListNode cur = head;
        ListNode nex = head;
        ListNode headA = null;
        int ans = size / 2;
        for (int i = 0; i < ans; i++) {
            nex = nex.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
        }
        headA = pre;
        ListNode headB = (size % 2 == 0 ? cur : cur.next);
        while (headA != null && headB!= null) {
            if (headA.val != headB.val) {
                return false;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return true;
    }
}

求出鏈表長度
找到中點
長度爲奇數則後半部分的鏈表頭爲cur.next(可以畫圖板模擬)
偶數則爲cur
每個元素比較找到不同則返回false
遍歷結束返回true
時間複雜度O(n)
空間複雜度O (1)

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