Skip to content

Commit 5e1b742

Browse files
committed
Reverse Linked List
1 parent 55fa402 commit 5e1b742

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
|66|[加一](https://leetcode-cn.com/problems/plus-one/)|[JavaScript](./algorithms/plus-one.js)|Easy|
1414
|136|[只出现一次的数字](https://leetcode-cn.com/problems/single-number/)|[JavaScript](./algorithms/single-number.js)|Easy|
1515
|189|[轮转数组](https://leetcode-cn.com/problems/rotate-array/)|[JavaScript](./algorithms/rotate-array.js)|Medium|
16+
|206|[反转链表](https://leetcode-cn.com/problems/reverse-linked-list/)|[JavaScript](./algorithms/reverse-linked-list.js)|Easy|
1617
|344|[反转字符串](https://leetcode-cn.com/problems/reverse-string/)|[JavaScript](./algorithms/reverse-string.js)|Easy|
1718
|349|[两个数组的交集](https://leetcode-cn.com/problems/intersection-of-two-arrays/)|[JavaScript](./algorithms/intersection-of-two-arrays.js)|Easy|
1819
|350|[两个数组的交集 II](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/)|[JavaScript](./algorithms/intersection-of-two-arrays-ii.js)|Easy|

algorithms/reverse-linked-list.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
* @param {ListNode} head
12+
* @return {ListNode}
13+
*/
14+
var reverseList = function (head) {
15+
let hNode;
16+
17+
while (head) {
18+
hNode = new ListNode(head.val, hNode);
19+
20+
head = head.next;
21+
}
22+
23+
return hNode || head;
24+
};
25+
26+
// 迭代法
27+
28+
/**
29+
* Definition for singly-linked list.
30+
* function ListNode(val, next) {
31+
* this.val = (val===undefined ? 0 : val)
32+
* this.next = (next===undefined ? null : next)
33+
* }
34+
*/
35+
/**
36+
* @param {ListNode} head
37+
* @return {ListNode}
38+
*/
39+
var reverseList = function(head) {
40+
let prev = null;
41+
let curr = head
42+
43+
while (curr) {
44+
let next = curr.next
45+
curr.next = prev
46+
prev = curr
47+
curr = next
48+
}
49+
50+
return prev
51+
};

0 commit comments

Comments
 (0)