Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. // task4_3.cpp: определяет точку входа для консольного приложения.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <assert.h>
  7.  
  8. using namespace std;
  9. /*
  10. ​Реализовать очередь с помощью двух стеков. Использовать стек, реализованный с помощью
  11.  
  12. динамического буфера.
  13. */
  14. class CStack
  15. {
  16. public:
  17. CStack(int size);
  18.  
  19. void push(int a);
  20. int pop();
  21.  
  22. bool IsEmpty() const
  23. {
  24. return top == -1;
  25. }
  26. ~CStack()
  27. {
  28. delete[] buffer;
  29. }
  30. private:
  31. int* buffer;
  32. int bufferSize;
  33. int top=-1;
  34. };
  35.  
  36. CStack::CStack(int size) :bufferSize(size), top(-1)
  37. {
  38. buffer = new int[size];
  39. }
  40. void CStack::push(int a)
  41. {
  42. if (top + 1 > bufferSize)
  43. {
  44. int* temp = new int[bufferSize * 2];
  45. for (int i = 0; i <= top; i++)
  46. {
  47. temp[i] = buffer[i];
  48. }
  49. delete[]buffer;
  50. buffer = temp;
  51. }
  52. buffer[++top] = a;
  53. }
  54. int CStack::pop()
  55. {
  56. if (top == -1)
  57. return -1;
  58. return buffer[top--];
  59.  
  60. }
  61.  
  62. class CQueue
  63. {
  64. public:
  65. CQueue(int size);
  66. bool empty()
  67. {
  68. return first.IsEmpty() && second.IsEmpty();
  69. }
  70. int pop();
  71. void push(int a);
  72. private:
  73. CStack first;
  74. CStack second;
  75. };
  76.  
  77. CQueue::CQueue(int size) :first(size), second(size)
  78. {}
  79. void CQueue::push(int a)
  80. {
  81. first.push(a);
  82. }
  83. int CQueue::pop()
  84. {
  85. if (!second.IsEmpty())
  86. return second.pop();
  87. else
  88. {
  89. while (!first.IsEmpty())
  90. {
  91. second.push(first.pop());
  92. }
  93. return second.pop();
  94. }
  95. }
  96.  
  97. void testingQueue()
  98. {
  99. //cout << "enter number of commands" << endl;
  100. int N;
  101. cin >> N;
  102. int failure = 0;
  103. CQueue tester(4);
  104. for (int i = 0; i < N; i++)
  105. {
  106. int command = 0;
  107. int number = 0;
  108. cin >> command;
  109. cin >> number;
  110. if (command == 3)
  111. {
  112. tester.push(number);
  113. }
  114. if (command == 2)
  115. {
  116. if (number != tester.pop())
  117. {
  118. failure++;
  119. }
  120. }
  121. }
  122. if (failure == 0)
  123. cout << "YES";
  124. else
  125. cout << "NO";
  126. }
  127.  
  128. int main()
  129. {
  130. testingQueue();
  131. //system("pause");
  132. return 0;
  133. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement