Advertisement
skb50bd

[template] myStack

Jul 28th, 2016
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <class T>
  5. class myStack {
  6. private:
  7.     T data;
  8.     myStack *next;
  9.  
  10. public:
  11.     myStack(T x, myStack *n): data(x), next(n) {}
  12.     myStack(): next(NULL) {}
  13.  
  14.     void push(T x) {
  15.         next = new myStack(x, next);
  16.     }
  17.  
  18.     bool pop() {
  19.         if (next != NULL) {
  20.             myStack *D = next;
  21.             next = next -> next;
  22.             delete D;
  23.             return true;
  24.         }
  25.         else return false;
  26.     }
  27.  
  28.     T top() {
  29.         if (next != NULL)
  30.             return next -> data;
  31.     }
  32.  
  33.     int count() {
  34.         int i = 0;
  35.         for (myStack *cur = next; cur != NULL; cur = cur -> next)
  36.             i++;
  37.         return i;
  38.     }
  39.  
  40.     void display() {
  41.         if (next != NULL)
  42.             for (myStack *cur = next; cur != NULL; cur = cur -> next)
  43.                 cout << cur -> data << " ";
  44.         else
  45.             cout << "< empty >";
  46.  
  47.         cout << endl;
  48.     }
  49.  
  50.     bool empty() {
  51.         return bool(next);
  52.     }
  53.  
  54.     void sort() {
  55.         if (next != NULL)
  56.             for (myStack *prev = next; prev -> next != NULL; prev = prev -> next)
  57.                 for (myStack *cur = prev -> next; cur != NULL; cur = cur -> next)
  58.                     if(prev -> data > cur -> data)
  59.                         swap(prev -> data, cur -> data);
  60.     }
  61. };
  62.  
  63.  
  64. int main() {
  65.     myStack <double> D;
  66.     D.push(2.1);
  67.     D.push(1.9);
  68.     D.push(3.1);
  69.     D.display();
  70.     D.sort();
  71.     D.display();
  72.     D.pop();
  73.     D.display();
  74.     D.pop();
  75.     cout << D.top() << endl;
  76.     D.pop();
  77.     D.display();
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement