fork 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 void 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. root = p;
  17. return;
  18. }
  19. if (data < root->data)
  20. push(root->left, data);
  21. else
  22. push(root->right, data);
  23. }
  24. static bool pop(Node *&root, int &data) {
  25. Node *p;
  26. if (root == 0)
  27. return false;
  28. if (root->left) {
  29. return pop(root->left, data);
  30. }
  31. p = root;
  32. data = p->data;
  33. root = p->right;
  34. delete p;
  35. return true;
  36. }
  37. };
  38.  
  39. class BinTree {
  40. private:
  41. Node *root;
  42. public:
  43. BinTree() { root = 0; }
  44. void pushNode(int data) { Node::push(root, data); }
  45. bool popNode(int &data) { return Node::pop(root, data); }
  46. };
  47.  
  48. int main() {
  49. const int n = 10;
  50. const int max = 1000;
  51. const int seed = 31415926;
  52. int data;
  53. BinTree *obj = new BinTree();
  54. srand(seed);
  55. for (int i = 0; i < n; i++) {
  56. data = rand() % max;
  57. obj->pushNode(data);
  58. }
  59. std::cout << "C++(2)" << std::endl;
  60. while (obj->popNode(data))
  61. std::cout << data << std::endl;
  62. delete obj;
  63. return 0;
  64. }
  65. /* end */
  66.  
Success #stdin #stdout 0.01s 2812KB
stdin
Standard input is empty
stdout
C++(2)
111
125
456
493
552
691
862
879
936
940