【问题标题】:How to implement a trie data structure in Pascal?如何在 Pascal 中实现 trie 数据结构?
【发布时间】:2013-01-10 15:50:27
【问题描述】:

我想尝试一下 Pascal。我开始是,但我的插入方法不能正常工作。这是程序的一部分:

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.

insertWord 过程总是得到一个单词,所以参数不会是""。

【问题讨论】:

  • 更好地指定“无法正常工作”。它有什么作用,你有什么期望?
  • 尝试添加第三个childNode时出现问题。在 if current^.deti[k]nil 的函数 getChildNode 中,指针指向错误的位置并且程序停止运行。

标签: dictionary pascal trie


【解决方案1】:

问题可能是记录没有像类一样自动归零?尝试添加

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

在新的(子节点)之后

【讨论】:

    猜你喜欢
    • 2011-04-30
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多