In: Computer Science
PYTHON-- create a method that prints items from a stack in a top to bottom order
If you have any queries please comment in the comments section I will surely help you out and if you found this solution to be helpful kindly upvote.
Solution :
Code :
# write a class to define a stack
class Stack:
# constructor to initialize an empty list for stack elements and
top as -1
def __init__(self):
self.elements = []
self.top = -1
# function to push the elements into the stack
def push(self, val):
# append the item passed in the function to the stack list
self.elements.append(val)
# increment top
self.top = self.top + 1
# function to pop the elements from the stack
def pop(self):
return self.elements.pop()
# function that print items of the stack from top to bottom
def top_to_bottom(self):
# iterate from top to bottom
for i in range(self.top,-1,-1):
# print the element
print(self.elements[i])
# create an object of stack class
s = Stack()
# push some elements into the stack
s.push(10)
s.push(20)
s.push(30)
s.push(40)
s.push(50)
# call the top to bottom function to print the elements from top to
bottom
s.top_to_bottom()
Output :