Skip to content

Instantly share code, notes, and snippets.

@furf
Created August 14, 2018 16:32
Show Gist options
  • Save furf/4331412d8c368c95868be00c1af0dd7a to your computer and use it in GitHub Desktop.
Save furf/4331412d8c368c95868be00c1af0dd7a to your computer and use it in GitHub Desktop.
Reverse a Linked List, because why not.
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;
}
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