Stack in C++ program is given below:
//Stacks in C++
#include <iostream>
using namespace std;
class stack{
public:
stack(int size = 10);
void push(int);
void pop(int &);
bool isFull(void);
bool isEmpty(void);
private:
int* array;
int size;
int top;
};
//--------------------------------------------------------
stack::stack(int size){
array = new int [size];
top = -1;
}
//--------------------------------------------------------
void stack::push(int x){
if (isFull()){
cout << "Stack is Full" << endl;
}
else{
array[++top] = x;
}
}
//--------------------------------------------------------
void stack::pop(int &x){
if (isEmpty()){
cout << "Stack is Empty" << endl;
}
else{
x = array[top--];
}
}
//--------------------------------------------------------
bool stack::isFull(void){
return top == size-1;
}
//--------------------------------------------------------
bool stack::isEmpty(void){
return top == -1;
}
////////////////////////////////////////////////////
int main(){
stack obj;
for (int i = 1; i<=5; i++){
cout << "Pushing " << i << endl;
obj.push(i);
}
cout << "Popping..." << endl;
int x;
for (i = 1; i<=5; i++){
obj.pop(x);
cout << x << endl;
}
return 0;
}
//Stacks in C++
#include <iostream>
using namespace std;
class stack{
public:
stack(int size = 10);
void push(int);
void pop(int &);
bool isFull(void);
bool isEmpty(void);
private:
int* array;
int size;
int top;
};
//--------------------------------------------------------
stack::stack(int size){
array = new int [size];
top = -1;
}
//--------------------------------------------------------
void stack::push(int x){
if (isFull()){
cout << "Stack is Full" << endl;
}
else{
array[++top] = x;
}
}
//--------------------------------------------------------
void stack::pop(int &x){
if (isEmpty()){
cout << "Stack is Empty" << endl;
}
else{
x = array[top--];
}
}
//--------------------------------------------------------
bool stack::isFull(void){
return top == size-1;
}
//--------------------------------------------------------
bool stack::isEmpty(void){
return top == -1;
}
////////////////////////////////////////////////////
int main(){
stack obj;
for (int i = 1; i<=5; i++){
cout << "Pushing " << i << endl;
obj.push(i);
}
cout << "Popping..." << endl;
int x;
for (i = 1; i<=5; i++){
obj.pop(x);
cout << x << endl;
}
return 0;
}
No comments:
Post a Comment