Advertisement
gha890826

期末考預告-3

Jun 10th, 2019
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. // Queue.cpp : 定義主控台應用程式的進入點。
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include "Header1.h"
  6. using namespace std;
  7.  
  8. template<class T>
  9. class node
  10. {
  11. public:
  12.     T num;
  13.     node<T> *next = NULL;
  14. };
  15.  
  16. template<class T>
  17. class queue
  18. {
  19. public:
  20.     queue<T>(){ cout << "***head= " << head << endl; }
  21.     void push(T);
  22.     void pop();
  23. private:
  24.     node<T> *head = new(node<T>);
  25. };
  26.  
  27. template<class T>
  28. void queue<T>::push(T n)
  29. {
  30.     node<T> *pos = head;
  31.     while (pos->next != NULL)
  32.     {
  33.         pos = pos->next;
  34.     }
  35.     pos->next = new(node<T>);
  36.     pos->next->num = n;
  37.     cout << "***push " << n << " to " << pos->next << endl;
  38. }
  39.  
  40. template<class T>
  41. void queue<T>::pop()
  42. {
  43.     if (head->next == NULL)
  44.     {
  45.         cout << "empty queue!\n";
  46.         return;
  47.     }
  48.     node<T> *del = head->next;
  49.     head->next = head->next->next;
  50.     cout << "pop " << del->num << " frome " << del << endl;
  51.     delete(del);
  52. }
  53.  
  54. void main()
  55. {
  56.     cout << "new qu1\n";
  57.     queue<int> qu1;
  58.     cout << "start int push\n";
  59.     qu1.push(1);
  60.     qu1.push(2);
  61.     qu1.push(3);
  62.     qu1.push(4);
  63.     cout << "start int pop\n";
  64.     qu1.pop();
  65.     qu1.pop();
  66.     qu1.pop();
  67.     qu1.pop();
  68.     qu1.pop();
  69.  
  70.     queue<char> qu2;
  71.     cout << "start char push\n";
  72.     qu2.push('f');
  73.     qu2.push('u');
  74.     qu2.push('c');
  75.     qu2.push('k');
  76.     cout << "start char pop\n";
  77.     qu2.pop();
  78.     qu2.pop();
  79.     qu2.pop();
  80.     qu2.pop();
  81.     qu2.pop();
  82.  
  83.     queue<float> qu3;
  84.     cout << "start float push\n";
  85.     qu3.push(1.1);
  86.     qu3.push(2.2);
  87.     qu3.push(3.3);
  88.     qu3.push(4.4);
  89.     cout << "start float pop\n";
  90.     qu3.pop();
  91.     qu3.pop();
  92.     qu3.pop();
  93.     qu3.pop();
  94.     qu3.pop();
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement