Write a program to show all the operations of a stack
#include <iostream>
#include <vector>
using namespace std;
class Stack
{
private:
vector<int> stack; // Using a vector to implement the stack
public:
void push(int element)
{
stack.push_back(element);
cout << "Pushed: " << element << endl;
}
void pop()
{
if (!stack.empty())
{
int poppedElement = stack.back();
stack.pop_back();
cout << "Popped: " << poppedElement << endl;
}
else
{
cout << "Stack underflow: Cannot pop from an empty stack." << endl;
}
}
void peek()
{
if (!stack.empty())
{
cout << "Top element: " << stack.back() << endl;
}
else
{
cout << "Stack is empty. Cannot peek." << endl;
}
}
bool isEmpty()
{
return stack.empty();
}
};
int main()
{
Stack myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
myStack.peek();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.peek(); // Try peeking when the stack is empty
return 0;
}

Comments
Post a Comment