Advertisement
AyanUpadhaya

Intro to Data Structure Stack

Jul 23rd, 2021
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. #stack means arranging objects on over another.
  2.  
  3. """stack data strucuture allows operations at one end which can be called top of the stack.We can add elements or remove elements only form this the stack.
  4.  
  5. In a stack the element inserted last in sequence will come out first as we can remove only from the top of the stack.
  6. Such feature is known as Last in First Out(LIFO) feature.
  7. The operations of adding and removing the elements is known as PUSH and POP.
  8. In the following program we implement it as add and and remove functions.
  9. We declare an empty list and use the append() and pop() methods to add and remove the data elements.
  10. """
  11.  
  12. class Stack:
  13.     def __init__(self):
  14.         self.stack = []
  15.  
  16.     def add(self, data):
  17.  
  18.         if data not in self.stack:
  19.             self.stack.append(data)
  20.             return True
  21.         else:
  22.             return False
  23.  
  24.     def peek(self):
  25.         return self.stack[-1]
  26.  
  27.     def remove(self):
  28.         if len(self.stack)<=0:
  29.             print("No element in stack found")
  30.         else:
  31.             return self.stack.pop()
  32.  
  33. abstack =  Stack()
  34.  
  35. abstack.add('Mon')
  36. abstack.add('Tue')
  37. abstack.add('Wed')
  38.  
  39. abstack.remove() #for removing last item
  40.  
  41. print(abstack.peek())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement