【问题标题】:Building Huffman encoding tree from ordered list从有序列表构建霍夫曼编码树
【发布时间】:2013-10-27 21:27:20
【问题描述】:

我正在从一个以最低频率开始的有序链表(按字母频率排序)构建一个霍夫曼编码树。创建树后,我遍历它,似乎树的实现不正确。当我遍历树时,有序链表中的一些节点似乎被遗漏了。 (我不认为这是因为我的遍历错误。)这是我的树代码:

//My class for the nodes in the ordered linked list that will be converted to a tree
class fList{
public:
  fList();
  int frequency;
  char letter;
  fList* next;
  fList* left;
  fList* right;
};

fList::fList(){
  frequency = 0;
  letter = NULL;
  next = NULL;
  left = NULL;
  right = NULL;
}
fList* head = NULL;

    .
    .
    .
    .
    .

//Create the huffman encoding tree from the linked list stored in head
while(head->next != NULL){
    fList *tree = new fList();
    fList *temp = new fList();
    fList *trail = new fList();

    /* Take the first two frequency numbers, add them, create a new node                             
     * with the total frequency number and have new node point to the first                          
     * two nodes (right child and left child) 
     */                                                       
    total = (head->frequency + head->next->frequency);
    tree->frequency = total;
    //Set a new head node
    tree->left = head;
    tree->right = head->next;
    head = head->next->next;
    tree->left->next = NULL;
    tree->right->next = NULL;

    //place tree node in its correct place in sorted list                                           
    temp = head;
    trail = temp;
    if(head->frequency >= tree->frequency){
      tree->next = head;
      head = tree;
    }

    else if(temp->next != NULL){
      while(temp != NULL){
        if(temp->frequency >= tree->frequency){
          tree->next = temp;
          trail->next = tree;
          break;
        }
        else{
          trail = temp;
          temp = temp->next;
        }
      }//while                 

    //insert at the end of list                                                                   
    if(temp == NULL){
      temp = tree->next;
      trail->next = tree;
    }
  }//else if !=NULL 

  else if(head == NULL || head->next == NULL) head = tree;
}

【问题讨论】:

  • 你试过调试了吗?

标签: c++ huffman-code


【解决方案1】:

在您发布的代码的末尾,在该行中

else if(temp->next = NULL && head != NULL) head = tree;

你无意中通过设置temp->next = NULL 截断了树,你可能想问temp->next == NULL。这可能就是为什么某些条目(由temp 链接的条目)被排除在最终结果之外的原因。

【讨论】:

  • 我实际上在我的代码中注释了该部分,但是当我在这里复制它时,我忘了把它拿出来。所以我的实际代码中没有这个。 (我在这里更新了我的代码以反映这一点。)谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
相关资源
最近更新 更多