-
-
Save PeteJobi/b344f87c694e461725bfdb259d960145 to your computer and use it in GitHub Desktop.
LinkedList Implementation with generics (typescript) Data structures
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 Noding<T> { | |
next: Noding<T> | any | |
data: T | |
constructor(data ?: T) { | |
this.data = data; | |
this.next = null; | |
} | |
} | |
class LinkedList<T> { | |
public size: number; //the size of the linked list | |
private head: Noding<T> | |
constructor() { | |
this.size = 0; | |
} | |
public append(data: T): void { | |
if (!this.head) { | |
this.head = new Noding(data); | |
this.size++ | |
return; | |
} | |
let current = this.head; | |
while (current.next) { | |
current = current.next | |
} | |
current.next = new Noding(data) | |
this.size++ | |
} | |
public prepend(data: T) { | |
let newhead = new Noding(data); | |
newhead.next = this.head; | |
this.head = newhead //change the head pointer to the preappended head | |
} | |
public deletewithvalue(data:T) { | |
if (this.head == null) return; | |
if (this.head.data == data) { | |
this.head = this.head.next; | |
return; | |
} | |
let current = this.head; | |
while (current.next != null) { | |
if (current.next.data == data) { | |
current.next = current.next.next; | |
return | |
} | |
current = current.next //move on to the next pointer | |
} | |
} | |
public replacewithvalue(data:T, newData: T) { | |
if (this.head == null) return; | |
if (this.head.data == data) { | |
this.head.data = newData; | |
return; | |
} | |
let current = this.head; | |
while (current.next != null) { | |
if (current.next.data == data) { | |
current.next.data = newData; | |
return | |
} | |
current = current.next //move on to the next pointer | |
} | |
} | |
} | |
const list = new LinkedList() | |
list.append(1) | |
list.append(122) | |
list.append(142) | |
list.prepend(666) | |
list.deletewithvalue(122) | |
list.replacewithvalue(142, 365) | |
console.log(list) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment