-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathReverseLinkedList.js
56 lines (48 loc) · 1.09 KB
/
ReverseLinkedList.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Source : https://leetcode.com/problems/reverse-linked-list/
// Author : Dean Shi
// Date : 2015-06-12
/**********************************************************************************
*
* Reverse a singly linked list.
*
* click to show more hints.
*
* Hint:
* A linked list can be reversed either iteratively or recursively. Could you implement both?
*
*
**********************************************************************************/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Recursion
*
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if (!head || !head.next) return head
let node = reverseList(head.next)
head.next.next = head
head.next = null
return node
};
/**
* Iteration
*
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let next, prev = null
while (head) {
[next, head.next] = [head.next, prev];
[prev, head] = [head, next]
}
return prev
};