0% found this document useful (0 votes)
8 views2 pages

C++ Stack Implementation Example

The document contains a C++ implementation of a Stack class that supports basic stack operations such as push, pop, peek, and print. It includes error handling for stack overflow and underflow conditions. The main function demonstrates the usage of the Stack class with a size of 5.

Uploaded by

ruthlessr19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

C++ Stack Implementation Example

The document contains a C++ implementation of a Stack class that supports basic stack operations such as push, pop, peek, and print. It includes error handling for stack overflow and underflow conditions. The main function demonstrates the usage of the Stack class with a size of 5.

Uploaded by

ruthlessr19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <iostream>

using namespace std;

class Stack {
private:
int* arr; // Pointer to the array
int top; // Index of the top element
int capacity; // Maximum size of stack

public:
// Constructor
Stack(int size) {
capacity = size;
arr = new int[capacity];
top = -1; // Stack is empty initially
}

// Destructor
~Stack() {
delete[] arr;
}

// Check if stack is empty


bool isEmpty() {
return top == -1;
}

// Check if stack is full


bool isFull() {
return top == capacity - 1;
}

// Push an element to the stack


void push(int val) {
if (isFull()) {
cout << "Stack overflow! Cannot push " << val << "\n";
return;
}
top++;
arr[top] = val;
cout << val << " pushed to stack\n";
}

// Pop an element from the stack


void pop() {
if (isEmpty()) {
cout << "Stack underflow! Cannot pop\n";
return;
}
int popped = arr[top];
top--;
cout << popped << " popped from stack\n";
}

// Peek / top element


void peek() {
if (isEmpty()) {
cout << "Stack is empty, nothing to peek\n";
return;
}
cout << "Top element is: " << arr[top] << "\n";
}

// Print stack elements


void print() {
if (isEmpty()) {
cout << "Stack is empty\n";
return;
}
cout << "Stack elements (top to bottom): ";
for (int i = top; i >= 0; i--) {
cout << arr[i] << " ";
}
cout << "\n";
}
};

// Usage Example
int main() {
Stack s(5); // Stack of size 5

[Link](10);
[Link](20);
[Link](30);
[Link](); // 30 20 10

[Link](); // Top element: 30

[Link]();
[Link](); // 20 10

[Link]();
[Link]();
[Link](); // Underflow

return 0;
}

You might also like