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

W13_直播檢討

W13_直播檢討

Vite系列#編譯設定

Vite系列#編譯設定

真相只有一個:資料串接偵錯流程

真相只有一個:資料串接偵錯流程


Comments