繁体   English   中英

从有序列表中构建霍夫曼编码树

[英]Building Huffman encoding tree from ordered list

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

//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;
}

在您发布的代码段的最后一行

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM