Skip to content

bobby0417/implement-a-stack-using-lists-with-operations

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

implement-a-stack-using-lists-with-operations

class Stack: def init(self): self.stack = [] # Initialize an empty list to represent the stack

def push(self, item):
    """Push an item onto the stack."""
    self.stack.append(item)
    print(f"Item {item} pushed to the stack.")

def pop(self):
    """Pop an item from the stack."""
    if not self.is_empty():
        popped_item = self.stack.pop()
        print(f"Item {popped_item} popped from the stack.")
    else:
        print("Stack is empty! Cannot pop.")

def display(self):
    """Display the elements of the stack."""
    if not self.is_empty():
        print("Current stack:", self.stack)
    else:
        print("Stack is empty!")

def is_empty(self):
    """Check if the stack is empty."""
    return len(self.stack) == 0

Create an instance of the Stack class

my_stack = Stack()

Display stack initially (should be empty)

my_stack.display()

Perform push operations

my_stack.push(10) my_stack.push(20) my_stack.push(30)

Display stack after pushing elements

my_stack.display()

Perform pop operations

my_stack.pop()

Display stack after popping an element

my_stack.display()

Pop all elements

my_stack.pop() my_stack.pop()

Try popping from an empty stack

my_stack.pop()

Display stack at the end

my_stack.display()

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published