The aim is to read in a file, calculate frequencies of each character and perform a huffman encoding, where the most common letters will be short binary codes i.e 001, and the least common will be longer, i.e 01000100.
I have created a linked list containing a sorted (in ascending order) list of all characters and their respective frequencies. This is passed to the function below. In this function I aimed to add the two lowest frequencies and build the binary tree like that until the length of the tree is 1. I'm unsure where to go from here, I know I have to look through the tree and see at which stage it goes left or right, then store a 0 (left) or 1 (right). - but i dont know how to build a function to do this!
void traverse_list(pqueue *list)
{
char letters[CHARACTERS] = { 0 };
int frequencies[CHARACTERS] = { 0 };
int j = 0, l = 0, len = 0;
node *temp = list->head;
tree *array[CHARACTERS];
while (temp != NULL)
{
letters[j] = temp->letter;
frequencies[j] = temp -> frequency;
temp = temp->next;
j++;
}
for (l = 0; l < CHARACTERS; l++)
{
if (frequencies[j])
{
tree* huffman = calloc(1, sizeof(tree));
huffman -> letter = letters[l];
huffman -> frequency = frequencies[l];
array[len++] = huffman;
}
}
while (len > 1)
{
tree* huffman = malloc(sizeof(tree));
huffman -> left = array[len--];
huffman -> right = array[len--];
huffman -> frequency = huffman -> left -> frequency + huffman -> right -> frequency;
array[len++] = huffman;
}
}
For easier reading the structs look like:
typedef struct Node
{
char letter;
int frequency;
struct Node *next;
}node;
typedef struct pqueue
{
node *head;
}pqueue;
typedef struct tree
{
struct tree *left;
struct tree *right;
char letter;
int frequency;
}tree;