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:
#include <iostream>
: This line includes the input and output stream library, allowing the program to perform input and output operations.#include <stack>
: This line includes the stack standard template library (STL) header, which provides the stack data structure implementation.std::stack<int> s;
: This line declares a stack named 's' that holds integers.s.push(1);
,s.push(2);
,s.push(3);
: These lines push the values 1, 2, and 3 onto the stack 's'.while (!s.empty()) { ... }
: This while loop continues as long as the stack 's' is not empty.std::cout << s.top() << " ";
: This line prints the top element of the stack 's' followed by a space.s.pop();
: This line removes the top element from the stack 's'.return 0;
: This statement indicates successful termination of the program.