You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bsearchtree.pas 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. { Copyright (C) 2005 Bas Steendijk and Peter Green
  2. For conditions of distribution and use, see copyright notice in zlib_license.txt
  3. which is included in the package
  4. ----------------------------------------------------------------------------- }
  5. {actually a hashtable. it was a tree in earlier versions}
  6. unit bsearchtree;
  7. interface
  8. uses blinklist;
  9. const
  10. hashtable_size=$4000;
  11. type
  12. thashitem=class(tlinklist)
  13. hash:integer;
  14. s:string;
  15. p:pointer;
  16. end;
  17. thashtable=array[0..hashtable_size-1] of thashitem;
  18. phashtable=^thashtable;
  19. {adds "item" to the tree for name "s". the name must not exist (no checking done)}
  20. procedure addtree(t:phashtable;s:string;item:pointer);
  21. {removes name "s" from the tree. the name must exist (no checking done)}
  22. procedure deltree(t:phashtable;s:string);
  23. {returns the item pointer for s, or nil if not found}
  24. function findtree(t:phashtable;s:string):pointer;
  25. implementation
  26. function makehash(s:string):integer;
  27. const
  28. shifter=6;
  29. var
  30. a,b:integer;
  31. begin
  32. result := 0;
  33. b := length(s);
  34. for a := 1 to b do begin
  35. result := (result shl shifter) xor byte(s[a]);
  36. end;
  37. result := (result xor result shr 16) and (hashtable_size-1);
  38. end;
  39. procedure addtree(t:phashtable;s:string;item:pointer);
  40. var
  41. hash:integer;
  42. p:thashitem;
  43. begin
  44. hash := makehash(s);
  45. p := thashitem.create;
  46. p.hash := hash;
  47. p.s := s;
  48. p.p := item;
  49. linklistadd(tlinklist(t[hash]),tlinklist(p));
  50. end;
  51. procedure deltree(t:phashtable;s:string);
  52. var
  53. p,p2:thashitem;
  54. hash:integer;
  55. begin
  56. hash := makehash(s);
  57. p := t[hash];
  58. p2 := nil;
  59. while p <> nil do begin
  60. if p.s = s then begin
  61. p2 := p;
  62. break;
  63. end;
  64. p := thashitem(p.next);
  65. end;
  66. linklistdel(tlinklist(t[hash]),tlinklist(p2));
  67. p2.destroy;
  68. end;
  69. function findtree(t:phashtable;s:string):pointer;
  70. var
  71. p:thashitem;
  72. hash:integer;
  73. begin
  74. result := nil;
  75. hash := makehash(s);
  76. p := t[hash];
  77. while p <> nil do begin
  78. if p.s = s then begin
  79. result := p.p;
  80. exit;
  81. end;
  82. p := thashitem(p.next);
  83. end;
  84. end;
  85. end.