Stack Program in Python



Python Implementation

Following is the implementation of basic operations (push(), pop(), peek(), isEmpty(), isFull()) in Stack ADT and printing the output in Python programming language −

class Stack: def __init__(self): self.stack = [] def add(self, data): if data not in self.stack: self.stack.append(data) return True else: return False # Use peek to look at the top of the stack def peek(self): return self.stack[-1] # Use list pop method to remove element def remove(self): if len(self.stack) <= 0: return ("No element in the Stack") else: return self.stack.pop() stk = Stack() stk.add(1) stk.add(2) stk.add(3) stk.add(4) stk.add(5) print("topmost element: ",stk.peek()) print("----Deletion operation in stack----") stk.remove() stk.peek() print("topmost element after deletion: ",stk.peek())

Output

topmost element: 5
----Deletion operation in stack----
topmost element after deletion: 4
Advertisements