-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseLinkedList.js
More file actions
51 lines (45 loc) · 1.13 KB
/
reverseLinkedList.js
File metadata and controls
51 lines (45 loc) · 1.13 KB
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
/*
* Reverse a singly linked list.
*
* Example:
*
* Input: 1->2->3->4->5->NULL
* Output: 5->4->3->2->1->NULL
* Follow up:
*
* 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;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if (!head || !head.next){
return head;
}
var reverseNode = {};
var counter = 0;
function traverse(node, reverseNode, counter){
if (!node.next){
var finalReverseNode = new ListNode(node.val);
finalReverseNode.next = reverseNode;
return finalReverseNode;
}
var newReverseNode = new ListNode(node.val);
if (counter === 0){
newReverseNode.next = null;
} else {
newReverseNode.next = reverseNode;
}
counter++;
return traverse(node.next, newReverseNode, counter);
}
return traverse(head, reverseNode, counter);
};