というわけで、P.52 練習問題2.2 1.

#include
using namespace std;

class stack {
  char *stck;
  int tos;
  char who;
  int size;
public:
  stack(char c, int _size);
  void push(char ch);
  char pop();
};

stack::stack(char c, int _size)
{
  size = _size;
  stck = (char *)malloc(size);
  tos = 0;
  who = c;
  cout << "Constructing stack " << who << "\n";
}

void stack::push(char ch)
{
  if (tos == size) {
    cout << "Stack " << who << " is full\n";
    return;
  }

  stck[tos] = ch;
  tos++;
}

char stack::pop()
{
  if (tos == 0) {
    cout << "Stack " << who << " is empty\n";
    return 0;
  }
  tos--;

  return stck[tos];
}

int main()
{
  int i;
  int size1, size2;

  cout << "Enter two sizes: ";
  cin >> size1 >> size2;

  stack s1('A', size1), s2('B', size2);

  s1.push('a');
  s2.push('x');
  s1.push('b');
  s2.push('y');
  s1.push('c');
  s2.push('z');

  for (i = 0; i < 5; i++) {
    cout << "Pop s1: " << s1.pop() << "\n";
  }

  for (i = 0; i < 5; i++) {
    cout << "Pop s2: " << s2.pop() << "\n";
  }

  return 0;
}


Comments

comments powered by Disqus