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 = class
  49. private
  50. root : pNode;
  51. flag : boolean;
  52. public
  53. constructor Create();
  54. procedure pushNode(data : integer);
  55. function popNode(var data : integer) : boolean;
  56. end;
  57.  
  58. constructor BinTree.Create();
  59. begin
  60. root := nil;
  61. flag := false;
  62. end;
  63.  
  64. procedure BinTree.pushNode(data : integer);
  65. begin
  66. root := push(root, data);
  67. flag := true
  68. end;
  69.  
  70. function BinTree.popNode(var data : integer) : boolean;
  71. begin
  72. root := pop(root, data);
  73. if (root = nil) then
  74. if (flag = true) then begin
  75. flag := false;
  76. popNode := true
  77. end else
  78. popNode := false
  79. else
  80. popNode := true
  81. end;
  82.  
  83. const
  84. N = 10;
  85. MAX = 1000;
  86. var
  87. root : BinTree;
  88. data, i : integer;
  89. begin
  90. root := BinTree.Create;
  91. randomize;
  92. i := 0;
  93. while (i < 10) do begin
  94. data := random(MAX);
  95. root.pushNode(data);
  96. i := i + 1
  97. end;
  98. while (root.popNode(data) = true) do
  99. writeln(data);
  100. root.Free
  101. end.
  102. { end }
  103.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty