Stack

About

Imagine a stack of dinner plates in a cafeteria. You can only place a new plate on the very top, and when you need a plate, you can only remove the one that is currently on the top.

Because of this, a Stack is known as a LIFO (Last In, First Out) data structure. The element that was added most recently is always the first one to be removed.

444333111222push()pop()

Complexities

Code Implementations

Python

if __name__ == "__main__":
    s = Stack()
    s.push(10)
    s.push(20)
    print("Top element (Peek):", s.peek())  # Expected: 20
    print("Popped element:", s.pop())       # Expected: 20
    print("Top element (Peek):", s.peek())  # Expected: 10
    print("Is stack empty?", s.is_empty())   # Expected: False

C++

int main() {
    Stack s;
    s.push(10);
    s.push(20);
    cout << "Top element (Peek): " << s.peek(); // Expected: 20
    s.pop();
    cout << "Top element after pop: " << s.peek(); // Expected: 10
    cout << (s.isEmpty() ? "Yes" : "No"); // Expected: No
}

Key Takeaways

Powered by Forestry.md