-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path206 Reverse Linked List.js
53 lines (47 loc) · 1.12 KB
/
206 Reverse Linked List.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
// Reverse a singly linked list.
// Uber Facebook Twitter Zenefits Amazon Microsoft Snapchat Apple Yahoo Bloomberg Yelp Adobe
// Show Tags
// Show Similar Problems
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// 60ms faster than ~93.19% & 35.1mb less than ~35.63%
const reverseList = head => {
if (head === [] || head === null) return head;
let current = head;
let prev = null;
while (current != null) {
let next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
};
// Recursive approach slightly less efficient @ 64ms && 36mb
// const reverseList = head => {
// if (head === [] || head === null || head.next === null) return head;
// let next = reverseList(head.next)
// head.next.next = head;
// head.next = null;
// return next;
// }