Created
May 27, 2015 09:48
-
-
Save bvsatyaram/f8a3775cf3e0af2142c8 to your computer and use it in GitHub Desktop.
LinkedList
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(arr) { | |
var list = null; | |
for(var i = arr.length -1; i >= 0; i--) { | |
list = { | |
value: arr[i], | |
rest: list | |
}; | |
} | |
return list; | |
} | |
function listToArray(list) { | |
var arr = []; | |
while(list != null) { | |
arr.push(list.value); | |
list = list.rest; | |
} | |
return arr; | |
} | |
function prepend(list, ele) { | |
return { | |
value: ele, | |
rest: list | |
}; | |
} | |
function nth(list, n) { | |
for(var i=1; i<=n-1;i++) { | |
list = list.rest; | |
if(list == nul) { | |
return undefined; | |
} | |
} | |
return list.value; | |
} | |
function insert(list, n, ele) { | |
var before = nth(list, n); | |
var tmp = before.rest; | |
before.rest = { | |
value: ele, | |
rest: tmp | |
} | |
} | |
var list = { | |
value: 1, | |
rest: { | |
value: 2, | |
rest: { | |
value: 3, | |
rest: null | |
} | |
} | |
}; | |
var arr = [1,2,3]; | |
console.log(arrayToList(arr)); | |
// => list | |
console.log(listToArray(list)); | |
// => arr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment