Created
August 14, 2018 16:32
-
-
Save furf/4331412d8c368c95868be00c1af0dd7a to your computer and use it in GitHub Desktop.
Reverse a Linked List, because why not.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildList(values) { | |
return values.reduceRight((next, value) => ({ value, next }), null); | |
} | |
function getValues(node) { | |
const values = []; | |
while (node) { | |
values.push(node.value); | |
node = node.next; | |
} | |
return values; | |
} | |
function reverseList(list) { | |
let source = list; | |
let target = null; | |
while (source !== null) { | |
const node = source; | |
source = node.next; | |
node.next = target; | |
target = node; | |
} | |
return target; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const list = buildList([1, 2, 3]); | |
// { | |
// "value": 1, | |
// "next": { | |
// "value": 2, | |
// "next": { | |
// "value": 3, | |
// "next": null | |
// } | |
// } | |
// } | |
const reverse = reverseList(list); | |
// { | |
// "value": 3, | |
// "next": { | |
// "value": 2, | |
// "next": { | |
// "value": 1, | |
// "next": null | |
// } | |
// } | |
// } | |
const values = getValues(reverse); | |
// [3, 2, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment