fork download
  1. program Main;
  2.  
  3. type
  4. Node = record
  5. data : integer;
  6. left : ^Node;
  7. right : ^Node
  8. end;
  9. pNode = ^Node;
  10.  
  11. function push(root : pNode; data : integer) : pNode;
  12. var
  13. r : pNode;
  14. begin
  15. if root = nil then begin
  16. new(r);
  17. r^.data := data;
  18. r^.left := nil;
  19. r^.right := nil;
  20. push := r;
  21. end else if data < root^.data then begin
  22. root^.left := push(root^.left, data);
  23. push := root
  24. end else begin
  25. root^.right := push(root^.right, data);
  26. push := root
  27. end
  28. end;
  29.  
  30. function pop(root : pNode; var data : integer) : pNode;
  31. var
  32. r : pNode;
  33. begin
  34. if root = nil then begin { never }
  35. pop := nil
  36. end else if root^.left <> nil then begin
  37. root^.left := pop(root^.left, data);
  38. pop := root
  39. end else begin
  40. r := root^.right;
  41. data := root^.data;
  42. dispose(root);
  43. pop := r
  44. end
  45. end;
  46.  
  47. type
  48. BinTree = object
  49. private
  50. root : pNode;
  51. flag : boolean;
  52. public
  53. procedure init;
  54. procedure pushNode(data : integer);
  55. function popNode(var data : integer) : boolean;
  56. end;
  57. pBinTree = ^BinTree;
  58.  
  59. procedure BinTree.init;
  60. begin
  61. root := nil;
  62. flag := false;
  63. end;
  64.  
  65. procedure BinTree.pushNode(data : integer);
  66. begin
  67. root := push(root, data);
  68. flag := true
  69. end;
  70.  
  71. function BinTree.popNode(var data : integer) : boolean;
  72. begin
  73. root := pop(root, data);
  74. if (root = nil) then
  75. if (flag = true) then begin
  76. flag := false;
  77. popNode := true
  78. end else
  79. popNode := false
  80. else
  81. popNode := true
  82. end;
  83.  
  84. const
  85. N = 10;
  86. MAX = 1000;
  87. var
  88. root : pBinTree;
  89. data, i : integer;
  90. begin
  91. new(root);
  92. root^.init;
  93. randomize;
  94. i := 0;
  95. while (i < 10) do begin
  96. data := random(MAX);
  97. root^.pushNode(data);
  98. i := i + 1
  99. end;
  100. while (root^.popNode(data) = true) do
  101. writeln(data);
  102. dispose(root);
  103. end.
  104. { end }
  105.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty