Advertisement
Guest User

Coda con le Pile

a guest
Jul 30th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. // IMPLEMENTARE UNA PILA CON I METODI DELLO STACK
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. template <class H> class LIFO{
  7. public:
  8.     virtual LIFO<H>* push(H x) = 0;
  9.     virtual H* pop() = 0;
  10.     virtual void print() = 0;  
  11. };
  12.  
  13. template <class H> class FIFO{
  14. public:
  15.     virtual FIFO<H>* enqueue(H x) = 0;
  16.     virtual H* dequeue() = 0;
  17.     virtual void print() = 0;  
  18. };
  19.  
  20. template <class T> class ArrayStack : public LIFO<T>{
  21.     T* q; // array
  22.     int top, length; // top: testa dello stack - length: dimensione dell'array
  23.  
  24. public:
  25.     ArrayStack(int length){
  26.         q = new T(length);
  27.         this->length = length;
  28.         top = 0;
  29.     }
  30.  
  31.     int isFull(){ return top == length; }
  32.     int isEmpty(){ return top == 0; }
  33.     int getSize(){ return top; }
  34.  
  35.     LIFO<T>* push(T x){
  36.         if(!isFull())
  37.             q[top++] = x;
  38.         return this;
  39.     }
  40.  
  41.     T* pop(){
  42.         if(!isEmpty())
  43.             return &q[--top];
  44.         return NULL;
  45.     }
  46.  
  47.     void print(){
  48.         for(int i = top-1; i >= 0; i--)
  49.             cout << q[i] << " ";
  50.         cout << endl;
  51.     }
  52. };
  53.  
  54. template <class P> class Queue: public FIFO<P>{
  55.     ArrayStack<P> *S1, *S2, *S3;
  56.     void _swap(ArrayStack<P>* A, ArrayStack<P>* B){
  57.         while(!A->isEmpty()) B->push(*(A->pop()));
  58.     }
  59.  
  60. public:
  61.     Queue(int length){
  62.         S1 = new ArrayStack<P>(length);
  63.         S2 = new ArrayStack<P>(length);
  64.         S3 = new ArrayStack<P>(2*length);
  65.     }
  66.  
  67.     FIFO<P>* enqueue(P x){
  68.         S1->push(x);
  69.         return this;
  70.     }
  71.  
  72.     P* dequeue(){
  73.         if(S2->isEmpty()) _swap(S1, S2);
  74.         return S2->pop();
  75.     }
  76.  
  77.     void print(){
  78.         _swap(S1, S3);
  79.         _swap(S2, S1);
  80.         _swap(S1, S3);
  81.         S3->print();
  82.         ArrayStack<P>* tmp = S2;
  83.         S2 = S3;
  84.         S3 = tmp;
  85.     }
  86.  
  87. };
  88.  
  89. int main(){
  90.     Queue<int> *Q = new Queue<int>(100);
  91.     Q->enqueue(5)->enqueue(3)->enqueue(7)->enqueue(1)->print();
  92.     Q->enqueue(4)->dequeue();
  93.     Q->print();
  94.     Q->dequeue();
  95.     Q->print();
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement