返回

回首 LeetCode,再忆回文:那些年我们在 LeetCode 上奋斗的日子

前端





导语

回文是一个有趣的概念,它指一个字符串或数字序列从前往后和从后往前读都是一样的。在计算机科学领域,链表是一种常用的数据结构,它由一系列通过指针连接的节点组成。一个回文链表是指链表中的元素从前往后和从后往前读都是相同的。

LeetCode 初级算法挑战:回文链表

LeetCode 是一个备受欢迎的在线算法挑战平台,它提供了一个系列的编程问题供用户解决。其中,初级算法挑战包含了一些相对简单的算法问题,非常适合初学者练习。回文链表是 LeetCode 初级算法挑战中的一个典型问题。

解题思路

为了检查一个链表是否为回文,我们可以采用以下步骤:

  1. 将链表分为两半。
  2. 将链表后半部分反转。
  3. 将反转后的链表与前半部分进行比较。
  4. 如果两个链表相等,则原始链表是回文,否则不是。

JavaScript 实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * Given the head of a singly linked list, return true if it is a palindrome.
 *
 * Example:
 *
 * Input: head = [1,2,2,1]
 * Output: true
 *
 * Input: head = [1,2,3,2,1]
 * Output: true
 *
 * Constraints:
 *
 * The number of nodes in the list is in the range [1, 10000].
 * 0 <= Node.val <= 9
 *
 * @param {ListNode} head
 * @return {boolean}
 */
const isPalindrome = (head) => {
  if (!head || !head.next) {
    return true;
  }

  // Find the middle of the linked list.
  let slow = head;
  let fast = head;
  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;
  }

  // Reverse the second half of the linked list.
  let prev = null;
  while (slow) {
    const next = slow.next;
    slow.next = prev;
    prev = slow;
    slow = next;
  }

  // Compare the first half and the second half of the linked list.
  while (head && prev) {
    if (head.val !== prev.val) {
      return false;
    }
    head = head.next;
    prev = prev.next;
  }

  return true;
};

结语

回文链表是一个有趣的算法问题,它可以帮助我们更好地理解链表这种数据结构。通过 LeetCode 的初级算法挑战,我们可以磨练我们的算法技能,并为未来的编程挑战做好准备。