Skip to content

Instantly share code, notes, and snippets.

@wkei
Last active March 14, 2018 02:50
Show Gist options
  • Save wkei/5e0c3e30d7d4fde8c492c4f0cc50c133 to your computer and use it in GitHub Desktop.
Save wkei/5e0c3e30d7d4fde8c492c4f0cc50c133 to your computer and use it in GitHub Desktop.
Reverse Linked List
function re (node, prevNode) {
node.next = prevNode.id
const prePreNode = findPrev(prePreNode)
if (prePreNode === null) {
prevNode.next = null
} else {
re(prevNode, prePreNode)
}
}
function findPrev (node) {
// something happens
}
// exec
re ({id: 0, next: null} /* the last node */, {id: 1, next: 0} /* next to the last node */)
// steps
{id: 2, next: 1} {id: 1, next: 0} {id: 0, next: null}
=>
{id: 2, next: 1} {id: 1, next: 0} {id: 0, next: 1}
=>
{id: 2, next: 1} {id: 1, next: 2} {id: 0, next: 1}
=>
{id: 2, next: null} {id: 1, next: 2} {id: 0, next: 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment