C++/Queue Stack/your stack

Материал из C\C++ эксперт
Перейти к: навигация, поиск

A classical stack operation using a string of characters.

<source lang="cpp">

  1. include <iostream>
  2. include <string.h>

using namespace std;

  1. 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);

}


 </source>


Define cast operator to cast stack to int

<source lang="cpp">

  1. 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;
  
}
 
   
 </source>


Stack class based on array

<source lang="cpp">

  1. include <iostream>

using namespace std;

  1. 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;

}


 </source>