fork(4) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. struct node {
  7. int value;
  8. node * next;
  9. node(int v, node * n = NULL) {
  10. value = v;
  11. next = n;
  12. }
  13. };
  14.  
  15. struct chain {
  16. node * head;
  17. int count;
  18. chain(node * h = NULL) {
  19. head = h;
  20. count = 0;
  21. }
  22. ~chain() {
  23. clear();
  24. }
  25. int push(int v) {
  26. head = new node(v, head);
  27. ++count;
  28. return v;
  29. }
  30. int pop() {
  31. int v = head->value;
  32. node * n = head;
  33. head = head->next;
  34. delete n;
  35. --count;
  36. return v;
  37. }
  38. int back() {
  39. return head->value;
  40. }
  41. void clear() {
  42. while(head != NULL) pop();
  43. }
  44. int size() {
  45. return count;
  46. }
  47. bool empty() {return !count;}
  48. } stack;
  49.  
  50. int main() {
  51. string s;
  52. while (cin >> s) {
  53. if (s == "exit") {cout << "bye\n"; return 0;}
  54. if (s == "push") {int x; cin >> x; stack.push(x); cout << "ok\n";}
  55. if (s == "pop")
  56. if (stack.empty()) cout << "error" << endl;
  57. else cout << stack.pop() << endl;
  58. if (s == "back")
  59. if (stack.empty()) cout << "error" << endl;
  60. else cout << stack.back() << endl;
  61. if (s == "clear") {stack.clear(); cout << "ok\n";}
  62. if (s == "size") {cout << stack.size() << endl;}
  63. }
  64. }
Success #stdin #stdout 0s 5496KB
stdin
push 2
push 3
push 5
back
size
pop
size
push 7
pop
clear
size
exit
stdout
ok
ok
ok
5
3
5
2
ok
7
ok
0
bye