mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
增加 234. 回文链表 JavaScript 版本
This commit is contained in:
@ -284,7 +284,41 @@ class Solution:
|
||||
## JavaScript
|
||||
|
||||
```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;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user