Stack operation
A stack is a fundamental data structure that follows the Last In, First Out (LIFO) principle, meaning the most recently added item is the first one to be removed. It can be visualized as a stack of plates, where you can only add or remove the top plate. Stacks typically support two main operations:
Additionally, some implementations may support other operations like peek (viewing the top element without removing it) and isEmpty (checking if the stack is empty).
Here's how a stack behaves:
Real-world use cases for stacks include:
Working of stack data structure
Initialization:
Push Operation:
Pop Operation:
Overflow and Underflow:
The following diagram illustrate the working structure of STACK:
As in the above stack operation, Elements are popped in the reversed order of their insertion, hence called Last In First Out (LIFO) or First In Last Out (FILO) data structure.
Algorithm for Array Implementation of Stack
Algorithm: Array Stack Implementation
Data:
- stack: Array to store elements of the stack
- MAX_SIZE: Maximum capacity of the stack
- TOP: Pointer to keep track of the top element in the stack
Operations:
1. InitializeStack()
2. Push(element)
3. Pop()
4. Peek()
5. IsEmpty()
6. IsFull()
Algorithm:
1. InitializeStack():
Set TOP = -1
2. Push(element):
if IsFull():
Print "Stack Overflow"
else:
Increment TOP
stack[TOP] = element
3. Pop():
if IsEmpty():
Print "Stack Underflow"
else:
element = stack[TOP]
Decrement TOP
return element
4. Peek():
if IsEmpty():
Print "Stack is empty"
else:
return stack[TOP]
5. IsEmpty():
return (TOP == -1)
6. IsFull():
return (TOP == MAX_SIZE - 1)
Write C++ program to implement stack and its operations
#include <iostream>
#define MAX_SIZE 100 // Maximum capacity of the stack
class Stack {
private:
int stack[MAX_SIZE];
int top;
public:
Stack() {
top = -1; // Initialize top to -1
}
void push(int element) {
if (isFull()) {
std::cout << "Stack Overflow\n";
} else {
top++;
stack[top] = element;
}
}
int pop() {
if (isEmpty()) {
std::cout << "Stack Underflow\n";
return -1; // Return some default value or throw an exception
} else {
int element = stack[top];
top--;
return element;
}
}
int peek() {
if (isEmpty()) {
std::cout << "Stack is empty\n";
return -1; // Return some default value or throw an exception
} else {
return stack[top];
}
}
bool isEmpty() {
return (top == -1);
}
bool isFull() {
return (top == MAX_SIZE - 1);
}
};
int main() {
Stack stack;
// Pushing elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Popping elements from the stack
std::cout << "Popped: " << stack.pop() << std::endl;
std::cout << "Popped: " << stack.pop() << std::endl;
// Peeking the top element
std::cout << "Top element: " << stack.peek() << std::endl;
return 0;
}