Nature is fairly organized in it's structure, and this organization help the smooth running of certain task. For example, animal poop, the poop is in the right state for the nutrifying bacterial in the soil to work on, this process then produce nutrients for plants, which in turn becomes food that we eat... Now that's one way to observe Nature's structure.
But in programming, Data also has to be organized in a way, that it can be easily retrieve, manipulated, and processed. One of the many ways data can be organized is the topic of this discussion. "Stack"
Stack is the organization of data as a stack, a stack of item. Just the way, products are stacked on each other in a retail store, such that the last item added into the stack, is the first item that can be taken out of the stack (provided you have sane laborers).
Here are the characteristic of the Stack data structure
- LIFO (Last In, First Out); the last item added onto the stack is the first item that can be retrieved.
It has the following operations.
push - to add item unto the stack
pop - to remove the last added item from the stack.
peek - to view the last added item to the stack.
isEmpty - to check, if the stack is empty.
isFull - to check, if the stack is filled (for fixed sized)
An obvious application of the stack data structure, is the way browser's history are organized. The organization of data in this case (browser history) allows for fast and easy retrieval of data (although, it might be a draw back in another case)
Implementation of the stack data structure in python
python
class Stack:
def __init__(self):
self.stack = []
def push(self, data):
self.stack.append(data)
def pop(self):
data = self.stack[-1]
del self.stack[-1]
return data
def peek(self):
return self.stack[-1]
def is_empty(self):
return self.stack == []
def size(self):
return len(self.stack)
#use the class
new_stack = Stack()
# add items to the stack
new_stack.push("banana")
new_stack.push("apple")
new_stack.push("watermelon")
# remove an item from the stack
new_stack.pop() #removes watermelon
new_stack.peek(); #returns apple
new_stack.is_empty() # returns false
new_stack.size() # returns 2
Top comments (0)