fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <exception>
  4. using namespace std;
  5.  
  6. struct node{
  7. int value;
  8. node *next;
  9. node():value(0), next(NULL){}
  10. node(int value, node *next)
  11. :value(value), next(next){}
  12. };
  13.  
  14. struct _queue{
  15. int _size;
  16. node *first;
  17. node *last;
  18. _queue():_size(0), first(NULL), last(NULL){}
  19.  
  20. void push (int v){
  21. node *new_node = new node(v, last);
  22. if(_size == 0){
  23. first = last = new_node;
  24. }
  25. else{
  26. last->next = new_node;
  27. last = new_node;
  28. }
  29. _size++;
  30. }
  31.  
  32. void pop(){
  33. if (_size > 0){
  34. int val = first->value;
  35. first = first->next;
  36. _size--;
  37. cout << val;
  38. }
  39. else throw 0;
  40. }
  41.  
  42. void front(){
  43. if (_size > 0) cout << first->value;
  44. else throw 0;
  45. }
  46.  
  47. int size(){
  48. return _size;
  49. }
  50.  
  51. void clear(){
  52. while (_size > 0){
  53. node *new_node = first->next;
  54. delete first;
  55. first = new_node;
  56. _size--;
  57. }
  58. first = NULL;
  59. last = NULL;
  60. }
  61. };
  62.  
  63.  
  64. int main()
  65. {
  66. _queue q;
  67. string s;
  68. int n;
  69. while (cin >> s){
  70. if (s == "size"){
  71. cout << q.size() << endl;
  72. }
  73. if (s == "push"){
  74. cin >> n;
  75. q.push(n);
  76. cout << "ok" << endl;
  77. }
  78. if (s == "pop"){
  79. try{
  80. q.pop();
  81. }
  82. catch(int e){cout << "error";}
  83. cout << endl;
  84. }
  85. if (s == "front"){
  86. try {
  87. q.front();
  88. }
  89. catch(int e){cout << "error";}
  90. cout<<endl;
  91. }
  92. if (s == "clear"){
  93. q.clear();
  94. cout << "ok" << endl;
  95. }
  96. if (s == "exit"){
  97. cout << "bye" <<endl;
  98. return 0;
  99. }
  100. }
  101. return 0;
  102. }
Success #stdin #stdout 0s 3420KB
stdin
size
push 1
size
push 2
size
push 3
size
exit
stdout
0
ok
1
ok
2
ok
3
bye