234. Palindrome Linked List


Posted by hata0833 on 2022-08-23

Given the head of a singly linked list, return true if it is a palindrome.
判斷鏈表是不是回文

思路:
需要注意幾個點,有奇數和偶數結點的兩種情況

  1. 先用快慢指針找出鏈表中點,同時把值推到棧中
  2. 奇數個結點,形如101,中點會停在0,棧中有1,此時需要把中點往後移一個
  3. 偶數個節點,形如1001,中點會停在第二個0,棧中有10,直接走while循環把棧中的值拿出來和中點一起做比較即可
var isPalindrome = function(head) {
    let now = head;
    // [1]的情況
    if (!now || !now.next) {
        return true;
    }
    let fast = now, slow = now, stack = [];
    while (fast && fast.next) {
        stack.push(slow.val);
        fast = fast.next.next;
        slow = slow.next;
    }
    // !fast -> even, !fast.next -> odd
    // 如果是odd回文,需要把中間的指針(即slow往後移一個)
    if (fast) {
        slow = slow.next;
    }
    while (slow) {
        const top = stack.pop();
        if (top != slow.val) {
            return false;
        }
        slow = slow.next;
    }
    return true;
};

#Leetcode







Related Posts

MTR04_0811

MTR04_0811

[T-SQL] Cursor範例

[T-SQL] Cursor範例

P/NP 問題(P versus NP problem)

P/NP 問題(P versus NP problem)


Comments