算法记录 - 回文链表

25 阅读1分钟

题目

234. 回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

思路

回文正常思路是头尾比较,但链表没法直接取最后节点数值,所以我们可以先找到链表中间节点,再进行反转, 就可以实现链表比较。

实现

同上实现三个函数 求链表中间节点 反转链表 链表节点比较

题解

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    let mid = midNode(head)
    let head2 = reverse(mid)
    while(head && head2) {
        if(head.val !== head2.val) {
            return false
        }
        head = head.next
        head2 = head2.next
    }
    return true
};

function midNode(head) {
    let slow = head
    let fast = head
    while(slow && fast && fast.next) {
        fast = fast.next.next
        slow = slow.next
    }
    return slow
}
function reverse(head) {
    let cur = head
    let res = null
    while(cur) {
        let temp = cur.next
        cur.next = res
        res = cur
        cur = temp
    }
    return res
}

复杂度

时间:O(n)

空间:O(1)

优化

已经是最优解,还有时间空间为n的解法,就是遍历链表,数组存值再进行头尾比较。