Skip to content

Instantly share code, notes, and snippets.

@jeff-ofobrukweta
Last active June 4, 2020 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeff-ofobrukweta/b29551f42f15dce9c3e3a7312139b087 to your computer and use it in GitHub Desktop.
Save jeff-ofobrukweta/b29551f42f15dce9c3e3a7312139b087 to your computer and use it in GitHub Desktop.
LinkedList Implementation with generics (typescript) Data structures
// this is for the Node
class MyNode<T>{
public data: T;
public next: MyNode<T> | any ;
constructor(data: T) {
this.data = data;
this.next = null
}
}
// this is for the linkedlist
class Mylinkedlist<T>{
public head: MyNode<T>;
public size: number;
constructor() {
this.size = 0
}
public append(data: T): void {
if (!this.head) {
this.head = new MyNode(data)
this.size++;
return
}
let current: MyNode<T> = this.head;
while (current.next != null) {
current = current.next;
}
current.next = new MyNode(data)
this.size++
}
public prepend(data: T): void {
let newHead: MyNode<T> = new MyNode(data)
newHead.next = this.head
this.head = newHead;
}
public deletenode(data: T): void {
//delete the node if its the head
let current: MyNode<T> = this.head
if (this.head == null) return; //if no head return
if (this.head.data == data) {
this.head = this.head.next;
this.size--;
return
}
// when you want to delete node inbetween another
while (current.next != null) {
if (current.next.data == data) {
current.next = current.next.next;
this.size--;
return
}
current = current.next;
}
}
public printLinkedlist(): void {
let current:MyNode<T> = this.head
let format: any = '';
while (current) {
if (current.data != null) {
format += "-->"+ current.data;
}
current = current.next;
}
// get the first part of linkedlist item
console.log("null"+format)
}
}
let l: Mylinkedlist<number> = new Mylinkedlist()
l.append(2)
l.append(12)
l.append(122)
l.append(142)
l.append(17)
l.append(22)
l.prepend(667)
// l.deletenode(667)
// l.deletenode(12)
l.printLinkedlist()
@jeff-ofobrukweta
Copy link
Author

You could make even better guys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment