Advertisement
Guest User

Untitled

a guest
May 27th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. class Stack
  2. {
  3. struct Element
  4. {
  5. int inf;
  6. Element *next;
  7. Element(int x, Element *p) :inf(x), next(p)
  8. {
  9.  
  10. }
  11. };
  12. Element *head; //указатель на вершину стека
  13. public:
  14. Stack() :head(0) //конструктор стека
  15. {}
  16. bool Empty()
  17. {
  18. return head == 0;
  19.  
  20. }
  21. int Pop()
  22. {
  23. if (Empty())
  24. {
  25. return 0;
  26.  
  27. }
  28. Element *r = head;
  29. int i = r->inf;
  30. head = r->next;
  31. delete r;
  32. return i;
  33. }
  34. void Push(int data) {
  35. head = new Element(data, head);
  36. }
  37. };
  38. class QueueException : public exception
  39. {
  40. public:
  41. QueueException(const string & message = "") :exception(message.c_str())
  42. {}
  43. };
  44.  
  45. template <class Item>
  46. class Queue
  47. {
  48. struct Melement
  49. {
  50. Item inf;
  51. Melement *next;
  52. Melement(Item x) :inf(x), next(0)
  53. {}
  54.  
  55. };
  56. Melement *head, *tail; //указатели на начало и конец очереди
  57. public:
  58. Queue() :head(0), tail(0)
  59. {}
  60. bool Empty()
  61. {
  62. return head == 0;
  63. }
  64. Item Get()
  65. {
  66. if (Empty())
  67. {
  68. throw QueueException("QueueExceprion: get - queue empty");
  69. }
  70. else //иначе извлекаем элемент из головы очереди
  71. {
  72. Melement *t = head;
  73. Item i = t->inf;
  74. head = t->next;
  75. if (head == NULL)
  76. {
  77. tail = NULL;
  78. }
  79. delete t;
  80. return i;
  81. }
  82.  
  83. }
  84. void Put(Item data)
  85. {
  86. Melement *t = tail; //устанавливаем вспомогательный указатель
  87. // на последний элемент очереди
  88. tail = new Melement(data); //формируется новый элемень, на
  89. //который будет указывать tail
  90. if (!head) //если до этого очередь была пуста, то новый
  91. {
  92. head = tail;
  93. }
  94. else
  95. {
  96. t->next = tail;
  97. }
  98. }
  99.  
  100. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement