Leetcode 206 - Reverse linked list

Note: We need a dummy node.
img

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:
img

1
2
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Iterative

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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) {
if (!head) {
return head;
}
let cur = head, prev = null;
while (cur) {
let tmp = cur.next;
cur.next = prev;
prev = cur;
cur = tmp;
}
return prev;
};

Recursive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var reverseList = function(head) {
return reverse(null, head);
};

var reverse = function (prev, head) {
if (!head) {
return prev;
}
let tmp = head.next;
head.next = prev;
prev = head;
head = tmp;
return reverse(prev, head);
}