simplest code for stack implementation in c++

Code for Stack Implementation in C++

#include <iostream>
#include <stack>

int main() {
    std::stack<int> s;

    s.push(1);
    s.push(2);
    s.push(3);

    while (!s.empty()) {
        std::cout << s.top() << " ";
        s.pop();
    }

    return 0;
}

Explanation:

  1. #include <iostream>: This line includes the input and output stream library, allowing the program to perform input and output operations.

  2. #include <stack>: This line includes the stack standard template library (STL) header, which provides the stack data structure implementation.

  3. std::stack<int> s;: This line declares a stack named 's' that holds integers.

  4. s.push(1);, s.push(2);, s.push(3);: These lines push the values 1, 2, and 3 onto the stack 's'.

  5. while (!s.empty()) { ... }: This while loop continues as long as the stack 's' is not empty.

  6. std::cout << s.top() << " ";: This line prints the top element of the stack 's' followed by a space.

  7. s.pop();: This line removes the top element from the stack 's'.

  8. return 0;: This statement indicates successful termination of the program.