Search⌘ K
AI Features

Key Operations of a Stack

Explore the fundamental operations of stack data structures in C++, focusing on how to implement and use push, pop, peek, isEmpty, isFull, and size in array-based stacks. Understand the LIFO principle, error checking, and performance considerations to effectively manage stack data in your programs.

With stack implementations using arrays and linked lists established, the next step is to examine the fundamental operations for interacting with a stack. These operations define the stack’s behavior and how its data is manipulated.

A stack supports several core operations, but they all revolve around the LIFO (Last in, first out) principle. Before we can add or remove elements, we often need to check the current state of the stack. Let us begin with two essential utility operations.

The isEmpty() operation

The isEmpty() method checks whether the stack is empty. This is crucial before attempting to remove or view elements, as popping an empty stack would result in an error.

Example: Consider a stack that currently holds {88, 95, 72, 80, 91}. The top index points to position 4 (where 91 is stored). Calling isEmpty() on this stack would return false because top is 4, not -1.

If we were to pop all five elements one by one, top would eventually become -1 again. At that point, calling isEmpty() would return true.

C++ implementation (array-based)

In an array-based stack, we check if top equals -1. Remember that we initialized top to -1 when creating an empty stack, so if it is still -1, no elements have been added.

C++ 17
#include <iostream>
#include <vector>
#include <stdexcept>
class ArrayStack {
private:
std::vector<int> data;
int topIndex;
int capacity;
public:
ArrayStack(int cap = 10) : capacity(cap), data(cap), topIndex(-1) {}
bool isEmpty() const {
return topIndex == -1;
}
};
int main() {
ArrayStack stack(10);
std::cout << "Is stack empty? " << (stack.isEmpty() ? "true" : "false") << std::endl;
// Output: true (stack is empty)
return 0;
}
The isEmpty() operation

The isFull() operation

The isFull() operation checks whether the stack has reached its maximum capacity. This is only relevant for array-based stacks with a fixed size. Before pushing a new element, we should check if there is space available.

Example: Consider a stack with capacity 5 that currently holds {88, 95, 72, 80, 91}. The top is 4, and the capacity is 5. Since top equals capacity - 1 (that is, ...