反转链表-简单
难度:简单
题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
1
2
2
题目解析:
递归: ```javascript var reverseList = function(head) { if(!head || !head.next) return head var next = head.next // 递归反转 var reverseHead = reverseList(next) // 变更指针 next.next = head head.next = null return reverseHead }; ```
循环:
var reverseList = function (head) {
if (!head || !head.next) return head;
var prev = null,
curr = head;
while (curr) {
// 用于临时存储 curr 后继节点
var next = curr.next;
// 反转 curr 的后继指针
curr.next = prev;
// 变更prev、curr
// 待反转节点指向下一个节点
prev = curr;
curr = next;
}
head = prev;
return head;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
尾递归
var reverseList = function (head) {
if (!head || !head.next) return head;
head = reverse(null, head);
return head;
};
var reverse = function (prev, curr) {
if (!curr) return prev;
var next = curr.next;
curr.next = prev;
return reverse(curr, next);
};
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
← 反转链表 II-中等 回文链表-简单 →