Created
April 1, 2019 22:00
-
-
Save Zodiase/f0aff3b9cccbc8490de3624cfa7b3dd8 to your computer and use it in GitHub Desktop.
TypeScript: Reverse Singly-linked List
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
class SinglyLinkedListNode { | |
public data: any = null; | |
public next: SinglyLinkedListNode = null; | |
} | |
class SinglyLinkedList { | |
public static fromArray(items: any[]): SinglyLinkedList { | |
const list = new SinglyLinkedList(); | |
list.head = items.reduceRight((acc, item) => { | |
const node = new SinglyLinkedListNode(); | |
node.data = item; | |
node.next = acc; | |
return node; | |
}, null); | |
return list; | |
} | |
public static reverse(list: SinglyLinkedList): SinglyLinkedList { | |
const newList = new SinglyLinkedList(); | |
let last: SinglyLinkedListNode = null; | |
let curr: SinglyLinkedListNode = list.head; | |
while (curr !== null) { | |
const newNode = new SinglyLinkedListNode(); | |
newNode.data = curr.data; | |
newNode.next = last; | |
last = newNode; | |
curr = curr.next; | |
} | |
newList.head = last; | |
return newList; | |
} | |
public head: SinglyLinkedListNode = null; | |
public toString(): string { | |
let curr = this.head; | |
let str = ''; | |
while (curr !== null) { | |
str += curr.data; | |
curr = curr.next; | |
} | |
return str; | |
} | |
} | |
const list = SinglyLinkedList.fromArray([1, 2, 3, 4]); | |
console.log(String(list)); | |
console.log(String(SinglyLinkedList.reverse(list))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment