Created
November 4, 2017 13:45
-
-
Save abdulhalim-cu/0ceb582fb28c3235b887386b48d483f2 to your computer and use it in GitHub Desktop.
Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, …
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
function arrayToList(array) { | |
var list=null; | |
for (var i=array.length - 1; i >= 0; i--) { | |
list = {value:array[i], rest:list}; | |
} | |
return list; | |
} | |
function listToArray(list){ | |
var array = []; | |
for(var node = list; node; node=node.rest) { | |
array.push(node.value); | |
} | |
return array; | |
} | |
function prepend(value, list) { | |
return {value:value, rest:list} | |
} | |
function nth(list, n) { | |
if (!list) | |
return "Undefined"; | |
else if (n==0) | |
return list.value; | |
else | |
return nth(list.rest, n - 1); | |
} | |
console.log(arrayToList([3,5,7])); | |
console.log(listToArray(arrayToList([3,5,7]))); | |
console.log(prepend(30,prepend(4,0))); | |
console.log(nth(arrayToList([4,6,2,21,2]),3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment