Skip to content

Instantly share code, notes, and snippets.

@furf
Last active April 29, 2016 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furf/ba970b1e4cd01a6bdf446d9c30ed185c to your computer and use it in GitHub Desktop.
Save furf/ba970b1e4cd01a6bdf446d9c30ed185c to your computer and use it in GitHub Desktop.
Reverse a linked list. Or something.
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