41 lines
903 B
JavaScript
41 lines
903 B
JavaScript
/**
|
|
* 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}
|
|
*/
|
|
const isPalindrome = function (head) {
|
|
|
|
};
|
|
|
|
/*
|
|
利用栈将链表的值存储起来,然后再从头开始遍历链表,比较每个节点的值和栈顶的值是否相等。
|
|
利用了回文的定义,正着和倒着应该是一样的。
|
|
*/
|
|
function f1(head) {
|
|
const stack = [];
|
|
let current = head;
|
|
|
|
// 第一步:将所有节点的值压入栈中
|
|
while (current) {
|
|
stack.push(current.val);
|
|
current = current.next;
|
|
}
|
|
|
|
// 第二步:从头开始重新遍历链表,同时与栈顶比较
|
|
current = head;
|
|
while (current) {
|
|
if (current.val !== stack.pop()) {
|
|
return false;
|
|
}
|
|
current = current.next;
|
|
}
|
|
|
|
return true;
|
|
}
|