Seal_of_approval

p74e5

May 17th, 2015
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. stack.h
  2.  
  3. #include <iostream>
  4. #include <cstdlib>
  5.  
  6. class Stack {
  7. private:
  8.     int* _stack;
  9.     int _size;
  10. public:
  11.     Stack() {
  12.         this->_size = 0;
  13.         this->_stack = (int *)malloc(0);
  14.         }
  15.     ~Stack() { this->empty(); }
  16.     void push(int item);
  17.  
  18.     int peek();
  19.     int pop();
  20.     int getSize();
  21.  
  22.     void empty();
  23. private:
  24.     void _extend();
  25.     void _shrink();
  26.     void _allocate();
  27. };
  28. ------------------------
  29.  
  30. stack.cpp
  31.  
  32. #include "Stack.h"
  33.  
  34. void Stack::push(int item) {
  35.    this->_extend();
  36.    this->_stack[this->_size-1] = item;
  37. }
  38.  
  39. int Stack::peek() {
  40.     return this->_stack[this->_size-1];
  41. }
  42.  
  43. int Stack::pop() {
  44.     int item = this->_stack[this->_size-1];
  45.     this->_shrink();
  46.     return item;
  47. }
  48.  
  49. int Stack::getSize() {
  50.     return this->_size;
  51. }
  52.  
  53. void Stack::empty() {
  54.     while (this->_size) this->_shrink();
  55. }
  56.  
  57. void Stack::_extend() {
  58.     this->_size++;
  59.     this->_allocate();
  60. }
  61.  
  62. void Stack::_shrink() {
  63.     this->_size--;
  64.     this->_allocate();
  65. }
  66.  
  67. void Stack::_allocate() {
  68.     this->_stack = (int *)realloc(this->_stack,
  69.                                   this->_size * sizeof(int));
  70. }
  71.  
  72. ---------
  73. main.cpp
  74.  
  75. #include "Stack.h"
  76. #include <cstdio>
  77. using namespace std;
  78.  
  79. int main(void) {
  80.     freopen("input.txt", "r", stdin);
  81.     freopen("output.txt", "w", stdout);
  82.     int size, x, y, tmp;
  83.     cin >> size >> x >> y;
  84.  
  85.     Stack* s = new Stack();
  86.  
  87.     for (int i = 0; i < size; i++) {
  88.         cin >> tmp;
  89.         s->push(tmp);
  90.     }
  91.  
  92.     Stack *result = new Stack();
  93.     while(s->getSize()) {
  94.         int item = s->pop();
  95.         if (item == x) {
  96.             result->push(y);
  97.         }
  98.         result->push(item);
  99.     }
  100.     while(result->getSize()) {
  101.         cout << result->pop() << " ";
  102.     }
  103.     cout << endl;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment