Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions TypeScript DS and Algorithms/linkedList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
export interface Node<T> {
value: T
next?: Node<T>
prev?: Node<T>
}

export class DoubleLinkedList<T> {
public head?: Node<T> = undefined;
public tail?: Node<T> = undefined;

add(value: T) {
const node: Node<T> = {
value,
next: undefined,
prev: undefined,
}
if (!this.head) {
this.head = node;
}
if (this.tail) {
this.tail.next = node;
node.prev = this.tail;
}
this.tail = node;
}

dequeue(): T | undefined {
if (this.head) {
const value = this.head.value;
this.head = this.head.next;
if (!this.head) {
this.tail = undefined;
}
else {
this.head.prev = undefined;
}
return value;
}
}

pop(): T | undefined {
if (this.tail) {
const value = this.tail.value;
this.tail = this.tail.prev;
if (!this.tail) {
this.head = undefined;
}
else {
this.tail.next = undefined;
}
return value;
}
}

*values() {
let current = this.head;
while (current) {
yield current.value;
current = current.next;
}
}
}
56 changes: 56 additions & 0 deletions TypeScript DS and Algorithms/queue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
export class Queue<T> {
queue: T[];
length: number;
readonly maxSize: number;

constructor(maxSize: number) {
this.maxSize = maxSize > 0 ? maxSize : 10;
this.length = 0;
this.queue = new Array<T>(this.maxSize);
}

isEmpty(): boolean {
return this.length === 0;
}

isFull(): boolean {
return this.length === this.maxSize;
}

enqueue(newItem: T): void {
if (this.isFull()) {
throw new Error('Queue overflow');
} else {
this.queue[this.length++] = newItem;
}
}

dequeue(): T {
if (this.isEmpty()) {
throw new Error('Queue underflow');
}

const retval = this.queue[0];

for (let i = 0; i < this.length; i++) {
this.queue[i] = this.queue[i + 1];
}

this.length--;
return retval;
}

peek(): T {
if (this.isEmpty()) {
throw new Error('Queue is empty');
}
return this.queue[0];
}

queueContents(): void {
console.log('Queue Contents');
for (let i = 0; i < this.length; ++i) {
console.log(`queue[${i}]: ${this.queue[i]}`);
}
}
}