Advertisement
jcvitanovic

Zad13

Dec 19th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. /*
  2. 19.12.2014
  3. Problem 13 You are provided with two stacks, as well as Pop and Push functions over
  4. them. Implement queue i.e. Enqueue and Dequeue using the available operations.
  5. */
  6.  
  7. #include<stdio.h>
  8. #include<vector>
  9. #include<iostream>
  10.  
  11. #define max 1000
  12. using namespace std;
  13.  
  14. class Stack {
  15.  
  16. private:
  17.     int size = 0;
  18.     vector<int> items;
  19. public:
  20.  
  21.     Stack(){
  22.         items = vector<int>(1);
  23.     }
  24.  
  25.     bool IsEmpty(){
  26.         return size == 0;
  27.     }
  28.     bool IsFull(){
  29.         return false;
  30.         //return size == max; // ?
  31.     }
  32.     int Pop(){
  33.         int popItem = items[size - 1];
  34.         size--;
  35.         if ((size > 0) && (size == items.size() / 4)){
  36.             items.resize(items.size() / 2);
  37.         }
  38.         return popItem;
  39.     }
  40.     void Push(int item){
  41.         size++;
  42.         items[size - 1] = item;
  43.         if (size == items.size()){
  44.             items.resize(items.size() * 2);
  45.         }
  46.     }
  47.     int Top(){
  48.         return items[size - 1];
  49.     }
  50.  
  51.  
  52. };
  53.  
  54. class Queue{
  55. private:
  56.     Stack s1;
  57.     Stack s2;
  58. public:
  59.     Queue(){
  60.         s1 = Stack();
  61.         s2 = Stack();
  62.     }
  63.     void Enqueue(int item){
  64.         s1.Push(item);
  65.  
  66.     }
  67.     int Dequeue(){
  68.         int retVal;
  69.         if (s2.IsEmpty()){
  70.             while (!s1.IsEmpty()){
  71.                 int item = s1.Pop();
  72.                 s2.Push(item);
  73.             }
  74.         }
  75.         retVal = s2.Pop();
  76.         return retVal;
  77.     }
  78.     bool IsEmpty(){
  79.         return s1.IsEmpty()&&s2.IsEmpty();
  80.     }
  81.  
  82. };
  83.  
  84. int main(){
  85.     Queue q;
  86.     for (int i = 0; i < 10; i++){
  87.         q.Enqueue(i);
  88.     }
  89.  
  90.     while (!q.IsEmpty()){
  91.         cout << q.Dequeue() << " ";
  92.     }
  93.  
  94.  
  95.  
  96.  
  97.  
  98.  
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement