LL13 判断链表是否为回文结构
约 218 字小于 1 分钟
2025-03-21
描述
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
链接
示例
输入: {1} 返回值: true
输入: {2,1} 返回值: false
输入: {1,2,2,1} 返回值: true
题解
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* {1} true
* {1,2,2,1} true
* {2,1} false
* @param head ListNode类 the head
* @return bool布尔型
*/
function isPail(head) {
// write code here
// 比较两个字符串,一个正向插入,一个反向插入
let f = "";
let b = "";
while (head) {
f += head.val;
b = `${head.val}${b}`;
head = head.next;
}
return f === b;
}
module.exports = {
isPail: isPail,
};