Skip to content

Instantly share code, notes, and snippets.

@Zodiase
Created April 1, 2019 22:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zodiase/f0aff3b9cccbc8490de3624cfa7b3dd8 to your computer and use it in GitHub Desktop.
Save Zodiase/f0aff3b9cccbc8490de3624cfa7b3dd8 to your computer and use it in GitHub Desktop.
TypeScript: Reverse Singly-linked List
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