fork(1) download
  1. #include <iostream>
  2. //#include <cstdlib>
  3. #include <stdlib.h>
  4.  
  5. class Node {
  6. private:
  7. int data;
  8. Node *left, *right;
  9. public:
  10. static Node *push(Node *root, int data) {
  11. Node *p;
  12. if (!root) {
  13. p = new Node();
  14. p->data = data;
  15. p->left = p->right = 0;
  16. return p;
  17. }
  18. if (data < root->data) {
  19. root->left = push(root->left, data);
  20. return root;
  21. } else {
  22. root->right = push(root->right, data);
  23. return root;
  24. }
  25. }
  26. static Node *pop(Node *root, int &data) {
  27. Node *p;
  28. if (root == 0)
  29. return 0;
  30. if (root->left) {
  31. root->left = pop(root->left, data);
  32. return root;
  33. }
  34. p = root->right;
  35. data = root->data;
  36. delete root;
  37. return p;
  38. }
  39. };
  40.  
  41. class BinTree {
  42. private:
  43. Node *root;
  44. bool flag;
  45. public:
  46. BinTree() {
  47. root = 0;
  48. flag = false;
  49. }
  50. void pushNode(int data) {
  51. root = Node::push(root, data);
  52. flag = true;
  53. }
  54. bool popNode(int &data) {
  55. root = Node::pop(root, data);
  56. if (!root) {
  57. if (flag) {
  58. flag = false;
  59. return true;
  60. } else
  61. return false;
  62. } else
  63. return true;
  64. }
  65. };
  66.  
  67. int main() {
  68. const int n = 10;
  69. const int max = 1000;
  70. const int seed = 31415926;
  71. int data;
  72. BinTree *obj = new BinTree();
  73. srand(seed);
  74. for (int i = 0; i < n; i++) {
  75. data = rand() % max;
  76. obj->pushNode(data);
  77. }
  78. std::cout << "C++(1)" << std::endl;
  79. while (obj->popNode(data))
  80. std::cout << data << std::endl;
  81. delete obj;
  82. return 0;
  83. }
  84. /* end */
  85.  
Success #stdin #stdout 0.01s 2860KB
stdin
Standard input is empty
stdout
C++(1)
111
125
456
493
552
691
862
879
936
940