warriorscats

Stack

May 28th, 2020
1,217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. struct Node {
  2.     int key, maxcurr;
  3.     Node *next;
  4.  
  5.     Node (int data): key (data), maxcurr (data), next (nullptr) {
  6.     }
  7. };
  8.  
  9. class Stiva {
  10. public:
  11.     Stiva (): peak (nullptr) {
  12.     }
  13.     void Push (int data) {
  14.         Node *temp = new Node (data);
  15.         if (!temp)
  16.             return;
  17.  
  18.         if (isEmpty ())
  19.             peak = temp;
  20.         else {
  21.             temp->next = peak;
  22.             temp->maxcurr = max (temp->maxcurr, peak->maxcurr);
  23.             peak = temp;
  24.         }
  25.     }
  26.     void Pop () {
  27.         if (isEmpty ())
  28.             return;
  29.  
  30.         Node *temp = peak;
  31.         peak = peak->next;
  32.         delete temp;
  33.     }
  34.     bool isEmpty () const{
  35.         return !peak;
  36.     }
  37.     int Top () const{
  38.         if (!isEmpty ())
  39.             return peak->key;
  40.         else
  41.             return - 1;
  42.     }
  43.     int Max () {
  44.         if (!isEmpty ())
  45.             return peak->maxcurr;
  46.         else
  47.             return - 1;
  48.     }
  49.     void Display () {
  50.         if (!isEmpty ()) {
  51.             stack <int> s;
  52.             while (!isEmpty ())
  53.                 cout << Top () << " ", s.push (Top ()), Pop ();
  54.             while (!s.empty ())
  55.                 Push (s.top ()), s.pop ();
  56.         } else
  57.             exit (EXIT_FAILURE);
  58.     }
  59.     ~Stiva () {
  60.         while (!isEmpty ())
  61.             Pop ();
  62.     }
  63.  
  64. private:
  65.     int key;
  66.     Node *peak;
  67. };
Add Comment
Please, Sign In to add comment