Explain the operations performed on stack with a program.
Q.) Explain the operations performed on stack with a program.
Subject: data structuresOperations Performed on a Stack
1. Push
The push operation adds an element to the top of the stack.
push(stack, element) {
stack.push(element);
}
where:
stack
is the stack to which the element is to be addedelement
is the element to be added
2. Pop
The pop operation removes and returns the element at the top of the stack.
pop(stack) {
if (stack.isEmpty()) {
throw new Error("Stack is empty");
}
return stack.pop();
}
where:
stack
is the stack from which the element is to be removed
3. Peek
The peek operation returns the element at the top of the stack without removing it.
peek(stack) {
if (stack.isEmpty()) {
throw new Error("Stack is empty");
}
return stack.peek();
}
where:
stack
is the stack from which the element is to be retrieved
4. IsEmpty
The isEmpty operation checks if the stack is empty.
isEmpty(stack) {
return stack.isEmpty();
}
where:
stack
is the stack to be checked
5. Size
The size operation returns the number of elements in the stack.
size(stack) {
return stack.size();
}
where:
stack
is the stack whose size is to be determined
Example
The following program demonstrates the operations on a stack:
#include
#include
using namespace std;
int main() {
stack stack;
// Push elements onto the stack
stack.push(1);
stack.push(2);
stack.push(3);
// Pop an element from the stack
int poppedElement = stack.pop();
// Peek at the element at the top of the stack
int topElement = stack.top();
// Check if the stack is empty
bool isEmpty = stack.empty();
// Get the size of the stack
int size = stack.size();
// Print the results
cout << "Popped element: " << poppedElement << endl;
cout << "Top element: " << topElement << endl;
cout << "Is stack empty: " << isEmpty << endl;
cout << "Size of stack: " << size << endl;
return 0;
}
Output:
Popped element: 3
Top element: 2
Is stack empty: false
Size of stack: 2