Sobes.tech
Junior — Middle

Can you explain the principle of a stack and its main features?

sobes.tech AI

Answer from AI

A stack is a data structure that operates on the Last In, First Out (LIFO) principle, meaning the most recently added element is the first to be removed.

Main features of a stack:

  • Operations:
    • push — add an element to the top of the stack.
    • pop — remove and return the top element.
    • peek or top — view the top element without removing it.
  • Uses:
    • Managing function calls (call stack).
    • Reversing the order of data processing.
    • Implementing undo actions.

Example of a simple stack in C++:

#include <iostream>
#include <stack>

int main() {
    std::stack<int> s;
    s.push(10);
    s.push(20);
    std::cout << s.top() << std::endl; // 20
    s.pop();
    std::cout << s.top() << std::endl; // 10
    return 0;
}