Created
April 26, 2014 04:53
-
-
Save adityasaxena/11312023 to your computer and use it in GitHub Desktop.
Reverse a Singly 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
| 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