Skip to content

Instantly share code, notes, and snippets.

@adityasaxena
Created April 26, 2014 04:53
Show Gist options
  • Save adityasaxena/11312023 to your computer and use it in GitHub Desktop.
Save adityasaxena/11312023 to your computer and use it in GitHub Desktop.
Reverse a Singly Linked List
function reverseList(list, newlist){
var newArray = newlist || [];
if(!Array.isArray(list)){
console.log('Not an array. Go Die!');
return;
}
if(list.length !== 2){
console.log('Invalid Array. Go Die!');
return;
}
newArray.unshift(list[0]);
if(!list[1]){
return newArray;
}
else{
return reverseList(list[1],newArray);
}
}
// Use it as follows for a singly linked list
// var arr = [1, [2, [3, null]]];
// console.log(reverseList(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment