Last active
April 29, 2016 16:10
-
-
Save furf/ba970b1e4cd01a6bdf446d9c30ed185c to your computer and use it in GitHub Desktop.
Reverse a linked list. Or something.
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 Node = { | |
value: null, | |
next: null, | |
}; | |
function createNode(value) { | |
return Object.assign(Object.create(Node), { value }); | |
} | |
function isNode(node) { | |
return Node.isPrototypeOf(node); | |
} | |
function linkNodes(node, ...nodes) { | |
if (!isNode(node)) { | |
throw new Error('Invalid Node.'); | |
} | |
node.next = nodes.length ? linkNodes(...nodes) : null; | |
return node; | |
} | |
function reverseLinkedList(node, next) { | |
const result = isNode(node.next) ? reverseLinkedList(node.next, node) : node; | |
node.next = isNode(next) ? next : null; | |
return result; | |
} | |
function $$(value) { | |
console.log(JSON.stringify(value, 0, 2)); | |
} | |
const list = linkNodes( | |
createNode('apple'), | |
createNode('banana'), | |
createNode('cherry') | |
); | |
$$(list); | |
// { | |
// "value": "apple", | |
// "next": { | |
// "value": "banana", | |
// "next": { | |
// "value": "cherry", | |
// "next": null | |
// } | |
// } | |
// } | |
const reversed = reverseLinkedList(list); | |
$$(reversed); | |
// { | |
// "value": "cherry", | |
// "next": { | |
// "value": "banana", | |
// "next": { | |
// "value": "apple", | |
// "next": null | |
// } | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment