Advertisement
AdamBB

Stack and Queue

Jan 18th, 2019
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. const int MAXINT = -2147483647;
  6.  
  7. struct slistEl
  8. {
  9.     slistEl *next;
  10.     int data;
  11. };
  12.  
  13. class stack
  14. {
  15. private: slistEl* S;
  16. public:stack();
  17.     ~stack();
  18.     bool empty(void);
  19.     slistEl* top(void);
  20.     void push(int v);
  21.     void pop(void);
  22. };
  23.  
  24. stack::stack()
  25. {
  26.     S = NULL;
  27. }
  28.  
  29. stack::~stack()
  30. {
  31.     while(S) pop();
  32. }
  33.  
  34. bool stack::empty(void)
  35. {
  36.     return !S;
  37. }
  38.  
  39. slistEl *stack::top(void)
  40. {
  41.     return S;
  42. }
  43.  
  44. void stack::push(int v)
  45. {
  46.     slistEl* e = new slistEl;
  47.  
  48.     e->data= v;
  49.  
  50.     e->next= S;
  51.     S = e;
  52. }
  53.  
  54. void stack::pop(void)
  55. {
  56.     if(S)
  57.     {
  58.         slistEl* e = S;
  59.         S = S->next;
  60.         delete e;
  61.     }
  62. }
  63.  
  64.  
  65. class queue
  66. {
  67. private:
  68.     slistEl *head;
  69.     slistEl *tail;
  70.  
  71. public:
  72.     queue();
  73.     ~queue();
  74.     bool empty(void);
  75.     int front(void);
  76.     void push(int v);
  77.     void pop(void);
  78. };
  79.  
  80. queue::queue()
  81. {
  82.     head = tail = NULL;
  83. }
  84.  
  85. queue::~queue()
  86. {
  87.     while(head) pop();
  88. }
  89.  
  90. bool queue::empty(void)
  91. {
  92.     return !head;
  93. }
  94.  
  95. int queue::front(void)
  96. {
  97.     if(head) return head -> data;
  98.     else return -MAXINT;
  99. }
  100.  
  101. void queue::push(int v)
  102. {
  103.     slistEl* p = new slistEl;
  104.     p->next= NULL;
  105.     p->data= v;
  106.     if(tail) tail->next= p;
  107.     else head= p;
  108.     tail = p;
  109. }
  110.  
  111. void queue::pop(void)
  112. {
  113.     if(head)
  114.     {
  115.         slistEl* p = head;
  116.         head = head->next;
  117.         if(!head) tail= NULL;
  118.         delete p;
  119.     }
  120. }
  121.  
  122. int main()
  123. {
  124.     stack S;
  125.     queue Q;
  126.  
  127.     int i,j;
  128.     cout<< "Stos:" << endl;
  129.     for(i = 1; i <= 10; i++) S.push(i);
  130.     while(!S.empty())
  131.     {
  132.         cout<< S.top()->data << endl;
  133.         S.pop();
  134.     }
  135.     cout<< "Kolejka:" << endl;
  136.     for(j = 1; j <= 10; j++) Q.push(j);
  137.     while(!Q.empty())
  138.     {
  139.         cout<< Q.front() << endl;
  140.         Q.pop();
  141.     }
  142. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement