Stack Basics
Basic Stack Operations in C++
BeginnerTopic: STL Containers Programs
C++ Stack Basics Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <stack>
using namespace std;
int main() {
// Create stack
stack<int> st;
// Push elements
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
cout << "Stack size: " << st.size() << endl;
cout << "Top element: " << st.top() << endl;
// Display stack (by popping)
cout << "\nStack elements (LIFO - Last In First Out):" << endl;
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
cout << endl;
// Stack for string reversal
stack<char> charStack;
string str = "Hello";
cout << "\nOriginal string: " << str << endl;
// Push all characters
for (char c : str) {
charStack.push(c);
}
// Pop to reverse
string reversed = "";
while (!charStack.empty()) {
reversed += charStack.top();
charStack.pop();
}
cout << "Reversed string: " << reversed << endl;
// Check balanced parentheses
stack<char> parenStack;
string expression = "((()))";
bool balanced = true;
for (char c : expression) {
if (c == '(') {
parenStack.push(c);
} else if (c == ')') {
if (parenStack.empty()) {
balanced = false;
break;
}
parenStack.pop();
}
}
if (parenStack.empty() && balanced) {
cout << "\nExpression '" << expression << "' is balanced" << endl;
} else {
cout << "\nExpression '" << expression << "' is not balanced" << endl;
}
return 0;
}Output
Stack size: 5 Top element: 50 Stack elements (LIFO - Last In First Out): 50 40 30 20 10 Original string: Hello Reversed string: olleH Expression '((()))' is balanced
Understanding Stack Basics
Stack is a LIFO (Last In First Out) container. Operations: push(), pop(), top(), empty(), size(). Only the top element is accessible. Common uses: 1) Expression evaluation, 2) Balanced parentheses checking, 3) Function call stack simulation, 4) Undo operations, 5) String reversal. All operations are O(1) time complexity.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.