Search code examples
dictionarypascaltrie

How to implement a trie data structure in Pascal?


I would like to make a try in Pascal. I started is but I the insert method does not work correctly. Here is a part of the program:

type PVrchol = ^Vrchol;
     Vrchol = record
       endOfTheWord:boolean;
       deti:array['a'..'z'] of PVrchol;
     end;
var trie:PVrchol;

FUNCTION getChildnode(current:PVrchol;k:char):PVrchol;
    Begin
      if current^.deti[k]<>nil then
         getChildnode:=current^.deti[k]
       else
         getChildNode:=nil;
    End;

PROCEDURE insertWord(word:string;var trie:PVrchol);
var i:integer;
  current, childNode:PVrchol;
Begin
  current:=trie;
  childNode:=current;
  for i:=1 to Length(word) do begin
      childNode:=getChildnode(current,word[i]);
      if childNode=nil then begin
        new(childNode);
        current^.deti[word[i]]:=childNode;
      end;
      current:=childNode;
  end;
  current^.endOfTheWord:=true;
End;
BEGIN
new(trie);
//there are some methods reading the words from input, and calling the insertWord procedure.
END.

The insertWord procedure always gets a word, so the parameter wont be "".


Solution

  • The problem might be that records are not automatically zeroed as classes are? Try adding

    fillchar(childnode,sizeof(childnode),#0);  
    

    after the new(childnode)