增加 234. 回文链表 JavaScript 版本

This commit is contained in:
jerryfishcode
2021-09-27 21:07:45 +08:00
committed by GitHub
parent 6158db21aa
commit 65901bdee4

View File

@ -284,7 +284,41 @@ class Solution:
## JavaScript ## JavaScript
```js ```js
var isPalindrome = function(head) {
const reverseList = head => {// 反转链表
let temp = null;
let pre = null;
while(head != null){
temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
// 如果为空或者仅有一个节点返回true
if(!head && !head.next) return true;
let slow = head;
let fast = head;
let pre = head;
while(fast != null && fast.next != null){
pre = slow; // 记录slow的前一个结点
slow = slow.next;
fast = fast.next.next;
}
pre.next = null; // 分割两个链表
// 前半部分
let cur1 = head;
// 后半部分。这里使用了反转链表
let cur2 = reverseList(slow);
while(cur1 != null){
if(cur1.val != cur2.val) return false;
// 注意要移动两个结点
cur1 = cur1.next;
cur2 = cur2.next;
}
return true;
};
``` ```