C++/Queue Stack/your stack
A classical stack operation using a string of characters.
#include <iostream>
#include <string.h>
using namespace std;
#define maxlen 80
class stack {
char str1[maxlen];
int first;
public:
void clear(void);
char top(void);
int empty(void);
int full(void);
void push(char chr);
char pop(void);
};
void stack::clear(void)
{
first=0;
}
char stack::top(void)
{
return (str1[first]);
}
int stack::empty(void)
{
return (first==0);
}
int stack::full(void)
{
return (first==maxlen-1);
}
void stack::push(char chr)
{
str1[++first]=chr;
}
char stack::pop(void)
{
return (str1[first-1]);
}
main( )
{
stack mystack;
char str[11]="0123456789";
mystack.clear( );
for(int i=0; (int) i<strlen(str);i++) {
if (!mystack.full( ))
mystack.push(str[i]);
cout << str[i] << endl;
}
while (!mystack.empty( ))
cout << mystack.pop( ) << endl;
return (0);
}
Define cast operator to cast stack to int
#include <iostream>
using namespace std;
const int SIZE=100;
class stack {
int stck[SIZE];
int tos;
public:
stack(void) {tos=0;}
void push(int i);
int pop(void);
operator int(void) {return tos;}
};
void stack::push(int i){
if(tos==SIZE){
cout << "Stack is full." << endl;
return;
}
stck[tos++] = i;
}
int stack::pop(void){
if(tos==0){
cout << "Stack underrun." << endl;
return 0;
}
return stck[--tos];
}
int main(void){
stack stck;
int i, j;
for(i=0; i<20; i++)
stck.push(i);
j = stck;
cout << j << " items on stack." << endl;
cout << (SIZE - stck) << " spaces open." << endl;
}
Stack class based on array
#include <iostream>
using namespace std;
#define ARR_SIZE 100
class stack
{
int stck[ARR_SIZE];
int stack_top;
public:
stack();
~stack();
void push(int i);
int pop();
};
stack::stack(void)
{
stack_top = 0;
cout << "Stack Initialized" << endl;
}
stack::~stack(void){
cout << "Stack Destroyed" << endl;
}
void stack::push(int i){
if (stack_top==ARR_SIZE)
{
cout << "Stack is full." << endl;
return;
}
stck[stack_top] = i;
stack_top++;
}
int stack::pop(void){
if (stack_top==0){
cout << "Stack underflow." << endl;
return 0;
}
stack_top--;
return stck[stack_top];
}
int main(void){
stack obj1, obj2;
obj1.push(1);
obj2.push(2);
obj1.push(3);
obj2.push(4);
cout << obj1.pop() << endl;
cout << obj1.pop() << endl;
cout << obj2.pop() << endl;
cout << obj2.pop() << endl;
}