If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Below is the C++ implementation of a stack using an array:
cppCopy code
#include <iostream> class Stack { private: int* array; int capacity; int top; public: Stack(int capacity) : capacity(capacity), top(-1) { array = new int[capacity]; } ~Stack() { delete[] array; } bool isEmpty() { return top == -1; } bool isFull() { return top == capacity - 1; } void push(int value) { if (isFull()) { std::cout << "Stack Overflow! Cannot push element " << value << std::endl; return; } array[++top] = value; } void pop() { if (isEmpty()) { std::cout << "Stack Underflow! Cannot pop element." << std::endl; return; } --top; } int peek() { if (isEmpty()) { std::cout << "Stack is empty. Cannot peek." << std::endl; return -1; } return array[top]; } }; int main() { Stack stack(5); stack.push(1); stack.push(2); stack.push(3); std::cout << "Top element: " << stack.peek() << std::endl; // Output: 3 stack.pop(); stack.push(4); while (!stack.isEmpty()) { std::cout << "Popped element: " << stack.peek() << std::endl; stack.pop(); } return 0; }In this implementation, the
Stackclass uses an integer array to store the elements of the stack. Thetopvariable keeps track of the index of the top element in the stack. Thepushmethod adds an element to the stack, thepopmethod removes the top element, and thepeekmethod returns the value of the top element without removing it.In the
mainfunction, we demonstrate how to use theStackclass by creating a stack of capacity 5. We push elements onto the stack, peek at the top element, and then pop elements until the stack becomes empty. The output will show the elements being pushed and popped, following the Last In First Out (LIFO) principle.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support