Skip to content

Commit 403ba8a

Browse files
committed
Palindrome Linked List
1 parent 5094d1c commit 403ba8a

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
|141|[环形链表](https://leetcode-cn.com/problems/linked-list-cycle/)|[JavaScript](./algorithms/linked-list-cycle.js)|Easy|
1616
|189|[轮转数组](https://leetcode-cn.com/problems/rotate-array/)|[JavaScript](./algorithms/rotate-array.js)|Medium|
1717
|206|[反转链表](https://leetcode-cn.com/problems/reverse-linked-list/)|[JavaScript](./algorithms/reverse-linked-list.js)|Easy|
18+
|234|[回文链表](https://leetcode-cn.com/problems/palindrome-linked-list/)|[JavaScript](./algorithms/palindrome-linked-list.js)|Easy|
1819
|344|[反转字符串](https://leetcode-cn.com/problems/reverse-string/)|[JavaScript](./algorithms/reverse-string.js)|Easy|
1920
|349|[两个数组的交集](https://leetcode-cn.com/problems/intersection-of-two-arrays/)|[JavaScript](./algorithms/intersection-of-two-arrays.js)|Easy|
2021
|350|[两个数组的交集 II](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/)|[JavaScript](./algorithms/intersection-of-two-arrays-ii.js)|Easy|

algorithms/palindrome-linked-list.js

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// 方法一:栈的后进先出
2+
3+
/**
4+
* Definition for singly-linked list.
5+
* function ListNode(val, next) {
6+
* this.val = (val===undefined ? 0 : val)
7+
* this.next = (next===undefined ? null : next)
8+
* }
9+
*/
10+
/**
11+
* 回文链表
12+
* @param {ListNode} head
13+
* @return {boolean}
14+
*/
15+
var isPalindrome = function (head) {
16+
let curr = head;
17+
let arr = [];
18+
19+
while (curr) {
20+
arr.push(curr.val);
21+
curr = curr.next;
22+
}
23+
24+
while (head) {
25+
if (arr.pop() !== head.val) {
26+
return false;
27+
}
28+
head = head.next;
29+
}
30+
31+
return true;
32+
};
33+
34+
35+
// 快慢节点 + 反转链表
36+
37+
/**
38+
* Definition for singly-linked list.
39+
* function ListNode(val, next) {
40+
* this.val = (val===undefined ? 0 : val)
41+
* this.next = (next===undefined ? null : next)
42+
* }
43+
*/
44+
/**
45+
* @param {ListNode} head
46+
* @return {boolean}
47+
*/
48+
var isPalindrome = function (head) {
49+
let slow = head,
50+
fast = head,
51+
prev = null;
52+
// 快慢指针找到 middle node
53+
while (fast) {
54+
slow = slow.next;
55+
fast = fast.next ? fast.next.next : fast.next;
56+
}
57+
// 反转后半部分链表
58+
while (slow) {
59+
let temp = slow.next;
60+
slow.next = prev;
61+
prev = slow;
62+
slow = temp;
63+
}
64+
// 依次比较
65+
while (head && prev) {
66+
if (head.val !== prev.val) {
67+
return false;
68+
}
69+
head = head.next;
70+
prev = prev.next;
71+
}
72+
73+
return true;
74+
};

0 commit comments

Comments
 (0)