STL stack in C++ (LIFO - Last In First Out) 🚀

 


The stack in C++ STL is a Last In, First Out (LIFO) data structure. This means the last element inserted will be the first element removed.

Key Features:
Follows LIFO order (like a stack of plates 📚).
Insertion & Deletion in O(1) time complexity.
Only top element can be accessed.
Implemented using deque (default), vector, or list.


1️⃣ Syntax & Declaration

#include <iostream>
#include <stack>  // Include stack library
using namespace std;

int main() {
    stack<int> s;  // Declaring a stack

    s.push(10);  // Push elements
    s.push(20);
    s.push(30);

    cout << "Top Element: " << s.top() << endl;

    return 0;
}

🔹 Output

Top Element: 30

Only the top element is accessible!


2️⃣ Stack Operations

🔹 Pushing Elements (push())

s.push(5);
s.push(10);
s.push(15);

Adds elements to the top.

🔹 Removing Elements (pop())

s.pop();  // Removes the top element

Removes the last inserted element.

🔹 Accessing Top Element (top())

cout << s.top();  // Returns the top element

Returns the most recently added element.

🔹 Checking if Stack is Empty (empty())

if (s.empty()) {
    cout << "Stack is empty";
}

Checks whether the stack is empty.

🔹 Getting Stack Size (size())

cout << s.size();  // Returns the number of elements

Returns the number of elements in the stack.


3️⃣ Stack Example (Push, Pop, Display)

#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> s;
    
    s.push(10);
    s.push(20);
    s.push(30);

    cout << "Stack Size: " << s.size() << endl;
    
    while (!s.empty()) {
        cout << s.top() << " ";  // Print top element
        s.pop();  // Remove top element
    }

    return 0;
}

🔹 Output

Stack Size: 3
30 20 10

Elements are removed in LIFO order.


4️⃣ Stack Using vector or list

By default, stack uses deque, but you can change the underlying container:

🔹 Using vector

stack<int, vector<int>> s;

🔹 Using list

stack<int, list<int>> s;

Using list allows faster insertions/deletions.


5️⃣ Reverse a String Using Stack

#include <iostream>
#include <stack>
using namespace std;

int main() {
    string str = "Hello";
    stack<char> s;

    for (char c : str) {
        s.push(c);
    }

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

    return 0;
}

🔹 Output

Reversed String: olleH

Stacks are useful for reversing strings!


6️⃣ Balanced Parentheses Check

#include <iostream>
#include <stack>
using namespace std;

bool isBalanced(string expr) {
    stack<char> s;
    
    for (char ch : expr) {
        if (ch == '(' || ch == '{' || ch == '[') {
            s.push(ch);
        } else {
            if (s.empty()) return false;
            char top = s.top();
            if ((ch == ')' && top == '(') ||
                (ch == '}' && top == '{') ||
                (ch == ']' && top == '[')) {
                s.pop();
            } else {
                return false;
            }
        }
    }

    return s.empty();
}

int main() {
    string expr = "{[()]}";
    cout << (isBalanced(expr) ? "Balanced" : "Not Balanced") << endl;
    return 0;
}

🔹 Output

Balanced

Stacks are useful for expression validation!


📌 Summary

LIFO (Last In First Out) structure.
push(), pop(), top(), size(), empty() operations.
Used for undo/redo, function calls, recursion, and expression evaluation.
Implemented using deque (default), vector, or list.

Would you like the STL queue next? 🚀

Post a Comment

0 Comments