0

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
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
PypypieYum
  • 37
  • 5

2 Answers2

0

A simple way to do this is:

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

See https://linuxize.com/post/python-list-reverse/ for explanation about reversing lists.

Roy Bubis
  • 101
  • 5
-1

We can have a function that prints the elements in reverse order. So we start our loop from size-1 and would print upto index zero by decrementing the index by 1. So that makes our function as:

def display(self): 
    for i in range(self.size()-1,-1,-1): 
        print(self.elements[i])
Rupal Shah
  • 314
  • 1
  • 10
  • 2
    See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem. – the Tin Man Mar 22 '22 at 05:04