Home > other >  How to create a function within a stack class that can display a stack in a last in first out way in
How to create a function within a stack class that can display a stack in a last in first out way in

Time:03-21

I have created a stack class with functions such as pop, push, peek etc.

How do I create another function within the class to print a stack in last in first out way?

My class:

class Thestack:

  def __init__(self):
    self.elements = []

  def push(self, data):
    self.elements.append(data)

  def pop(self):
    if self.elements:
        return self.elements.pop()
    else:
        return None

  def top(self):
    return self.elements[-1]

  def size(self):
    return len(self.elements)

I have tried that with s.pop():

def display(self):
      while len(self.elements) > 0:
        print(self.pop())

But then the stack is empty.

is that anyway to retain/restore the order/ the original stack after displaying the stack?

I want to achieve something like this:

Thestack.push(7)
Thestack.push(8)
Thestack.push(9)
Thestack.Display()
print("Size = "   str(Thestack.size()))

Output:
9
8
7
Size = 3

CodePudding user response:

A simple way to do this is:

for element in reversed(self.elements):
    print(element)

CodePudding user response:

def display(self): 
    for i in range(self.size()-1,-1,-1): 
        print(self.elements[i])
  • Related