反转链表
-> 题目描述
Reverse Linked List
反转一个链表
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
1
2
3
2
3
反转链表一般有迭代法和递归法,能不能使用两种解法都实现
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
-> 解法
点击查看
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let curr = head
let prev = null
while(curr){
prev = new ListNode(curr.val, prev)
curr = curr.next
}
return prev
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-> 总结
iteratively
var reverseList = function(head) {
let curr = head
let prev = null
let next = null
while(curr){
next = curr.next
curr.next = prev
prev = curr
curr = next
}
return prev
};
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
recursively
var reverseList = function(head) {
return _reverse(head, null)
};
function _reverse(curr, prev) {
if (curr == null) return prev
const next = curr.next
curr.next = prev
return _reverse(next, curr)
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
编辑此页 (opens new window)
更新于: 2020-09-11 15:20