Stack is one of the important Data Structure, beginners in coding or data structures are scared of data structures but it's implementation is easy once you understand the basics of Data Structures.
In this article, we will see the simplest implementation of Stack in Python, if you want in any other programming language do comment I will provide simplest code in that particular language.
class Stack: | |
def __init__(self): | |
self.items=[] | |
def isEmpty(self): | |
return self.items==[] | |
def push(self,x): | |
return self.items.append(x) | |
def pop(self): | |
return self.items.pop() | |
def top(self): | |
return self.items[len(self.items)-1] | |
def size(self): | |
return len(self.items) |
Explanation -
1. First, we are implementing stack using lists here.
2. Create a class named Stack.
3. Define the format of Stack, like above we initialized list. ( self.items = [] ). It's important because we are going to perform all operations around this list and implement Stack.
4. Define following operations -
- isEmpty() - This will check whether stack is empty or not. It is for preventing underflow. Underflow occurs when stack has no element and you try to pop element out of stack.
- push(x) - When you want to add item in Stack, pass that item as a parameter in push. Push is implemented using append in list. Like in list you append item, same in stack.
- pop() - When you want to delete item from Stack, pop it from list.
- top() - Top returns top element of the Stack.
- size() - Size returns the length of Stack. Length of stack is the number of items in the stack.
I hope the concept of Stack implementation is clear. If you have any doubt do comment, I will help you out.
Comments
Post a Comment