Intro to Stacks

Jaskomal
2 min readJul 26, 2021

Another linear data structure are Stacks. Stacks are very similar to Queues with a minor difference. While Queues add to the back of the structure Stacks are the opposite. With stacks add to the head and last one added is the first one selected. Like arrays you can use the push and pop methods to add and remove from a stack, the peek method can also be used to see data that is at the top of the stack. A real world example is racking weights at the gym the first plate you grab is the last one that was put on.

Stacks are used with linked lists as the underlying structure. So the first item in a stack would be the head of the linked list and the tail at the bottom. You can set a size limit on a stacks to control how much data is pushed into it, if you attempt to push more data than the size restriction you will get a stack overflow and if you try to pull from a empty stack you will get a stack underflow.

class Stack {// Array is used to implement stackconstructor()     {       this.items = [];     }// Functions to be implemented// push(element){// push element into the items     this.items.push(element);}// pop()    pop() {     if (this.items.length == 0)     return "Underflow";    return this.items.pop();}// peek()peek(){// return the top most element from the stack// but does'nt delete it.   return this.items[this.items.length - 1];}// isEmpty()isEmpty() {// return true if stack is empty    return this.items.length == 0;}// printStack()printStack() {   var str = "";   for (var i = 0; i < this.items.length; i++)   str += this.items[i] + " ";   return str;}} 

--

--