题解 | #判断一个链表是否为回文结构#

判断一个链表是否为回文结构

https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/

function isPail(head) {
if (head === null || head.next === null) {
return true
}
// 3.使用快慢指针
let fast = head,
slow = head,
current = head;
// 遍历链表,移动快慢指针
while (fast.next !== null && fast.next.next !== null) {
slow = slow.next;
fast = fast.next.next;
}
// 此时当快指针移动到末端时,慢指针移动到中间,反转慢指针之后的链表
let reverseListHead = reverseList(slow);
// 遍历链表,判断两个链表是否相等
while (current !== null && reverseListHead !== null) {
if (current.val !== reverseListHead.val) {
return false
}
current = current.next;
reverseListHead = reverseListHead.next;
}
return true;
}
//反转链表
function reverseList(current) {
let pre = null,
curr = current;
while (curr != null) {
let nextNode = curr.next;
curr.next = pre;
pre = curr;
curr = nextNode;
}
return pre;
}

module.exports = {
isPail : isPail
};


全部评论

相关推荐

一表renzha:手写数字识别就是一个作业而已
点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务