Guest User

queue_clean.c++

a guest
Aug 28th, 2014
1,908
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. class Stack {
  2.   private:
  3.     int value;
  4.     const Stack *next;
  5.     Stack( int _value, const Stack *_next = 0 ) : value(_value), next(_next) { }
  6.   public:
  7.     const Stack* push( int _value ) const {
  8.       return new Stack(_value, this);
  9.     }
  10.     bool empty() const {
  11.       return !this;
  12.     }
  13.     int top() const {
  14.       assert(this);
  15.       return value;
  16.     }
  17.     const Stack* pop() const {
  18.       assert(this);
  19.       return next;
  20.     }
  21.     static const Stack *null;
  22. };
  23. const Stack *Stack::null = 0;
  24.  
  25. class Queue {
  26.   private:
  27.     int size, help2_size;
  28.     const Stack *main, *help, *main2, *help2;
  29.     Queue( int _size, int _help2_size, const Stack *_main, const Stack *_help,
  30.        const Stack *_main2, const Stack *_help2 )
  31.       : size(_size), help2_size(_help2_size), main(_main), help(_help),
  32.         main2(_main2), help2(_help2) {}
  33.     Queue* morph() {
  34.       if (help2_size == -1) {
  35.         help2_size = size;
  36.         help2 = Stack::null;
  37.         main2 = main;
  38.       }
  39.       if (help2_size > 0) {
  40.         help2_size--;
  41.         help2 = help2->push(main2->top());
  42.         main2 = main2->pop();
  43.       }
  44.       if (help2_size == 0) {
  45.         help = help2;
  46.         help2_size = -1;
  47.         help2 = main2 = Stack::null;
  48.       }
  49.       return new Queue(size, help2_size, main, help, main2, help2);
  50.     }
  51.   public:
  52.     Queue() : size(0), help2_size(-1) {
  53.       main = help = main2 = help2 = Stack::null;
  54.     }
  55.     const Queue* push( int value ) const {
  56.       return Queue(size + 1, help2_size, main->push(value), help, main2, help2).morph();
  57.     }
  58.     bool empty() const {
  59.       return size == 0;
  60.     }
  61.     int top() const {
  62.       return help->top();
  63.     }
  64.     const Queue* pop() const {
  65.       assert(size);
  66.       return Queue(size - 1, help2_size == -1 ? -1 : help2_size - 1,
  67.            main, help->pop(), main2, help2).morph();
  68.     }
  69. };
Advertisement
Add Comment
Please, Sign In to add comment