Skip to content

Instantly share code, notes, and snippets.

@avdotion
Created July 27, 2018 22:17
Show Gist options
  • Save avdotion/1733c25b6bb79b3adfde61c024faa7ac to your computer and use it in GitHub Desktop.
Save avdotion/1733c25b6bb79b3adfde61c024faa7ac to your computer and use it in GitHub Desktop.
Implementations (Stack, List, Queue)
/**
* Stack implementation
* https://www.wikiwand.com/en/Stack_(abstract_data_type)
*/
export class Stack {
/**
* array implementation
* without shift (trying to be O(1) for adding and deleting)
* @param {Number} [maxsize=-1] [maxsize may be equal to -1 for dynamic]
*/
constructor(maxsize=-1) {
this.__items = new Array();
this.size = 0;
this.__maxsize = maxsize;
}
/**
* add an item to the stack
* @param {Number} item [the new top]
*/
push(item) {
if (this.size+1 <= this.__maxsize || __maxsize === -1) {
this.size++;
this.__items.push(item);
} else {
throw 'Stack is overloaded';
}
}
/**
* grab the top item from the stack
* @return {Number} [the top]
*/
pop() {
if (this.size > 0) {
this.size--;
return this.__items.pop();
} else {
throw 'Stack is empty';
}
}
}
class ListNode {
constructor(value=undefined) {
this.data = value;
this.next = undefined;
this.previous = undefined;
}
}
export class List {
constructor() {
this.size = 0;
this.head = undefined;
this.tail = undefined;
}
insert(item) {
let node = new ListNode(item);
if (this.head === undefined) {
this.head = this.tail = node;
} else {
this.tail.next = node;
node.previous = this.tail;
this.tail = node;
}
this.size++;
}
search(data) {
let currentNode = this.head;
let found = false;
while (currentNode !== undefined && !found) {
if (currentNode.data === data) {
found = true;
} else {
currentNode = currentNode.next;
}
}
if (currentNode === undefined) {
throw 'Data is out of the list';
} else {
return currentNode;
}
}
delete(data) {
let currentNode = this.head;
let previousNode = undefined;
let found = false;
while (currentNode !== undefined && !found) {
if (currentNode.data === data) {
found = true;
} else {
previousNode = currentNode;
currentNode = currentNode.next;
}
}
if (currentNode === undefined) {
throw 'Data is out of the list';
}
this.size--;
if (previousNode === undefined) {
self.head = currentNode.next;
} else {
previousNode.next = currentNode.next;
}
}
}
export class Queue {
constructor(maxsize=-1) {
this.size = maxsize;
this.__maxsize = maxsize;
this.items = new List();
}
push(item) {
if (this.size+1 <= this.__maxsize || maxsize === -1) {
this.size++;
this.push(item);
} else {
throw 'Queue is out of space'
}
}
pop() {
let temp = this.head;
this.head = this.head.next;
this.size--;
return temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment