Created
February 16, 2015 12:27
-
-
Save boutell/5e31025e7e29d0fa4d91 to your computer and use it in GitHub Desktop.
Reversing a linked list in JavaScript
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
var list = { | |
name: 'bob', | |
next: { | |
name: 'dick', | |
next: { | |
name: 'harry' | |
} | |
} | |
}; | |
console.log('FORWARD'); | |
var node = list; | |
while (node) { | |
console.log(node.name); | |
node = node.next; | |
} | |
console.log('BACKWARD'); | |
node = list; | |
// recursive descent | |
reverse(node); | |
function reverse(node) { | |
if (node.next) { | |
reverse(node.next); | |
console.log(node.name); | |
} else { | |
console.log(node.name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment