Untitled

 avatar
unknown
plain_text
a year ago
1.3 kB
13
Indexable
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
class Stack:
    def __init__(self):
        self.top = None
    def push(self, x):
        new_node = Node(x)
        new_node.next = self.top
        self.top = new_node
        print(f"{x} pushed to stack")
    def pop(self):
        if self.top is None:
            print("Stack is empty")
            return -9999
        x = self.top.data
        self.top = self.top.next
        return x
    def display(self):
        if self.top is None:
            print("Stack is empty")
            return
        temp = self.top
        print("Stack elements:", end=" ")
        while temp:
            print(temp.data, end=" ")
            temp = temp.next
        print()
# Main execution
stack = Stack()
while True:
    print("\n1. Push\n2. Pop\n3. Display\n4. Exit")
    ch = int(input("Enter your choice: "))

    if ch == 1:
        x = int(input("Enter a number: "))
        stack.push(x)

    elif ch == 2:
        x = stack.pop()
        if x != -9999:
            print(f"Popped value: {x}")

    elif ch == 3:
        stack.display()

    elif ch == 4:
        print("Exiting...")
        break

    else:
        print("Invalid choice")
    
        
Editor is loading...
Leave a Comment