Stacks - rohit120582sharma/Documentation GitHub Wiki

Stacks are a LIFO data structure where the last element added to the stack will be the first element removed from the stack

Stacks are used to handle function invocations (the call stack), for operations like undo/redo, and for routing (remember pages you have visited and go back/forward) and much more!

They are not a built in data structure in JavaScript, but are relatively simple to implement

Insert and remove are both O(1)


class Node {
	constructor(value){
		this.value = value;
		this.next = null;
	}
}
class Stack {
	constructor(){
		this.first = null;
		this.last = null;
		this.size = 0;
	}
	push(value){
		var newNode = new Node(value);
		if(!this.first){
			this.first = newNode;
			this.last = newNode; 
		}else{
			newNode.next = this.first;
			this.first = newNode;
		}
		this.size++;
		return this.size;
	}
	pop(){
		if(!this.first){
			return null;
		}
		var removeNode = this.first;
		if(this.first === this.last){
			this.last = null;
		}else{
			this.first = removeNode.next;
		}
		removeNode.next = null;
		this.size--;
		return removeNode;
	}
}
⚠️ **GitHub.com Fallback** ⚠️