Skip to content

Instantly share code, notes, and snippets.

@PeteJobi
Forked from jeff-ofobrukweta/linkedlist.ts
Last active June 3, 2020 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PeteJobi/b344f87c694e461725bfdb259d960145 to your computer and use it in GitHub Desktop.
Save PeteJobi/b344f87c694e461725bfdb259d960145 to your computer and use it in GitHub Desktop.
LinkedList Implementation with generics (typescript) Data structures
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