Created
May 24, 2015 20:46
-
-
Save martinkuba/953cfa87303572fb621b to your computer and use it in GitHub Desktop.
Linked list
This file contains hidden or 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 node = { | |
| next: null, | |
| value: null, | |
| create: function(value, next) { | |
| var inst = Object.create(this); | |
| inst.value = value; | |
| inst.next = next; | |
| return inst; | |
| } | |
| }; | |
| function createLinkedList(arr) { | |
| var root = node.create(arr[0]); | |
| var item, nextItem; | |
| item = root; | |
| for (var i = 1; i < arr.length; i++) { | |
| nextItem = node.create(arr[i]); | |
| item.next = nextItem; | |
| item = nextItem; | |
| } | |
| return root; | |
| } | |
| function reverse(root) { | |
| var previous, current, next; | |
| current = root; | |
| while (current.next) { | |
| next = current.next; | |
| current.next = previous; | |
| previous = current; | |
| current = next; | |
| } | |
| current.next = previous; | |
| return current; | |
| } | |
| function reverseRecurse(root) { | |
| return reverse(null, root); | |
| function reverse(previous, current) { | |
| var next = current.next; | |
| current.next = previous; | |
| if (!next) return current; | |
| return reverse(current, next); | |
| } | |
| } | |
| function printLinkedList(root) { | |
| var item = root; | |
| while (item) { | |
| console.log(item.value); | |
| item = item.next; | |
| } | |
| } | |
| var list1 = createLinkedList([1, 2, 3, 4, 5]); | |
| var reversed = reverseRecurse(list1); | |
| var reversed = reverse(list1); | |
| printLinkedList(reversed); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment