-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathProblem73.js
42 lines (36 loc) · 1012 Bytes
/
Problem73.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
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^reverseLinkedList" }] */
// Problem 73
//
// This problem was asked by Google.
//
// Given the head of a singly linked list, reverse it in-place.
//
// https://leetcode.com/problems/reverse-linked-list/
//
// O(N) Time complexity
// O(1) Space complexity
// N is the number of elements in the linked list
function reverseLinkedList(head) {
// return reverseLinkedListRecursive(head);
return reverseLinkedListIterative(head);
}
function reverseLinkedListIterative(head) {
let newHead = null;
while (head !== null) {
const { next } = head;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
function reverseLinkedListRecursive(head) {
return reverseLinkedListHelper(head, null);
}
function reverseLinkedListHelper(head, newHead) {
if (head === null) return newHead;
const { next } = head;
head.next = newHead;
return reverseLinkedListHelper(next, head);
}
export default reverseLinkedList;