0% found this document useful (0 votes)
2 views

Implementation of Stack

The document contains a C++ implementation of a Stack class that supports basic operations such as push, pop, peek, and checking if the stack is empty. It includes error handling for stack overflow and underflow conditions. The main function demonstrates the usage of the Stack class by pushing elements onto the stack and then popping them off while displaying the top element.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Implementation of Stack

The document contains a C++ implementation of a Stack class that supports basic operations such as push, pop, peek, and checking if the stack is empty. It includes error handling for stack overflow and underflow conditions. The main function demonstrates the usage of the Stack class by pushing elements onto the stack and then popping them off while displaying the top element.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Implementation of Stack

#include <iostream>
using namespace std;

class Stack {
private:

int top;

int arr[100];

public:

Stack() { top = -1; }

void push(int x)
{

if (top >= 99) {


cout << "Stack overflow" << endl;
return;
}

arr[++top] = x;
cout << "Pushed " << x << " to stack\n";
}
int pop()
{

if (top < 0) {
cout << "Stack underflow" << endl;
return 0;
}

return arr[top--];
}

int peek()
{

if (top < 0) {
cout << "Stack is empty" << endl;
return 0;
}

return arr[top];
}

bool isEmpty()
{
return (top < 0);
}
};

int main()
{

Stack s;

s.push(10);
s.push(20);
s.push(30);

cout << "Top element is: " << s.peek() << endl;

cout << "Elements present in stack : ";

while (!s.isEmpty()) {

cout << s.pop() << " ";


}
return 0;
}

You might also like