描述
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数链表节点数 0≤n≤10^5
,链表中每个节点的值满足 |val| <= 10^7 ;
示例
输入:
{1}
返回值:
true
示例2
输入:
{2,1}
返回值:
false
说明:
2->1
示例3
输入:
{1,2,2,1}
返回值:
true
说明:
1->2->2->1
思路: 回文结构是指正反序完全一致的支付串,解决方法就是把链表中的值转成字符串,在做比较;
代码:
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
function isPail( head ) {
// write code here
let arr = [];
while(head){
arr.push(head.val);
head = head.next;
}
let str1 = arr.join();
let str2 = arr.reverse().join();
if(str1 === str2){
return true;
}else{
return false;
}
}
module.exports = {
isPail : isPail
};
来自牛客编程题 https://www.nowcoder.com/exam/oj