Stack Data Structure in Javascript, Python and Ruby
Abhishek Sharma Gaur
Posted on May 13, 2023
A stack is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack and the only element that can be removed is the element that is at the top of a stack, just like a pile of books.
Stack is an ordered list of similar data types following the LIFO(Last in First out) principle. Here the push() function is used to insert new elements into the Stack and the pop() function is used to remove the topmost element from the stack.
Algorithm for PUSH operation
- Check if the stack is full or not.
- If the stack is full, exit the program.
- If the stack is not full, then increment the top and add the element.
Algorithm for POP operation
- Check if the stack is empty or not.
- If the stack is empty, print the underflow error and exit the program.
- If the stack is empty, print the element at the top and decrement the top.
Time complexity
Push: O(1)
Pop: O(1)
Size: O(1)
The functions associated with stack are:
empty() – Returns whether the stack is empty – Time Complexity: O(1)
size() – Returns the size of the stack – Time Complexity: O(1)
top() / peek() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
pop() – Deletes the topmost element of the stack – Time Complexity: O(1)
print - To print the stack
Below we have a Javascript program implementing a stack data structure
class Stack {
constructor(){
this.stack = [];
}
push = (item) => {
return item ? this.stack.push(item) : "do nothing";
};
pop = () => this.stack.pop();
isEmpty = () => (this.stack.length === 0 ? true : false);
size = () => this.stack.length
peek = () => this.stack[-1]
print = () =>
console.log("stack:",JSON.stringify(this.stack));
}
Below we have a Python program implementing a stack data structure
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
return self.items.insert(0, item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
return len(self.items)
def print(self):
return print("Stack is:", self.items)
Below we have a Ruby program implementing a stack data structure
class Stack
attr_reader :item
@@contents = []
def initialize(item)
@item = item
@@contents << item
end
def pop
@@contents.pop
end
def push(item)
@@contents.push(item)
end
def print
puts "#{@@contents}"
end
def peek
puts "#{@@contents.last}"
end
def size
puts "#{@@contents.length}"
end
end
Posted on May 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.