Introduction.

https://youtu.be/I37kGX-nZEI

It is a linear data structure that follows a particular order in which the operations are performed.

LIFO (Last In, First Out).

<aside> 💡 This strategy states that the element that is inserted last will come out first. You can take a pile of plates kept on top of each other as a real-life example. The plate which we put last is on the top and since we remove the plate that is at the top, we can say that the plate that was put last comes out first.

</aside>

Stack-data-structure.webp

Use int is type value

# include <iostream>
# include <stack>

int main()
{
    std::stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
    s.push(5);

    std::cout << "size: " << s.size() << std::endl;
    std::cout << "top: " << s.top() << std::endl;

    s.pop();
    std::cout << "size: " << s.size() << std::endl;
    std::cout << "top: " << s.top() << std::endl;

    return 0;
}

output

size: 5
top: 5
size: 4
top: 4

Use std::staring is the type value

# include <iostream>
# include <stack>

int main()
{
    std::stack<std::string> s;
    s.push("Hello");
    s.push("World");
    s.push("!");

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

    return 0;
}

output

!
World
Hello

Operation's

Push

The PUSH operation is used to insert a new element in the Stack. PUSH operation inserts a new element at the top of the stack.

Push-operation-Stack-data-structure.webp

<aside> ⚠️ If we try to insert a new element in the full stack (array has limited size), a stack overflow condition occurs. It means that we cannot add more elements to the stack.

</aside>

<aside> 💡 To avoid this situation, we can use a linked list instead of the array because the linked list has a dynamic size. We just need to add one more node with the data.

</aside>

Pop

The POP operation is to remove an element from the top of the stack. The element deleted is the recently inserted element in the Stack.

Pop-operation-Stack-data-structure.webp