I'm trying to write a simple C code for the following function:
Given an encoding for the letters a-d:
'a'->00, 'b'->01, 'c'->10, 'd'->11,
and a node in a linked-list defined as:
typedef struct listNode{
unsigned char data;
struct listNode* next;
}ListNode;
typedef struct list{
ListNode* head;
ListNode* tail;
}List;
where head
points to the first node of the list, and the tail
to the last one.
I need to write a function char* SumList(List arr[], int n)
, which returns a string which contains all the encoded letters in all the nodes of all lists in arr in row.
This is what I wrote so far:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int isBitISet(char, int);
typedef struct listNode {
unsigned char data;
struct listNode* next;
} ListNode;
typedef struct list {
ListNode* head;
ListNode* tail;
} List;
int isBitISet(char ch, int i) {
char mask;
mask=1<<i;
return (mask & ch);
}
int totalNodes(List arr[], int n) {
int i;
int counter=0;
for (i=0; i<n; ++i) {
ListNode* head= arr[i].head;
while (head!=NULL) {
counter++;
head=head->next;
}
}
return counter;
}
char* whatToadd(char data) {
int a, b;
a=isBitISet(data, 0);
b=isBitISet(data, 1);
char* result;
result=(char *) calloc(2, sizeof(char));
if ((a!=0) && (b!=0))
result="d";
else if ((a!=0) && (b==0))
result="b";
else if ((a==0) && (b!=0))
result="c";
else
result="a";
return result;
}
char* SumLists(List arr[], int n) {
char* final;
int nodes=totalNodes(arr, n);
final= (char*) calloc(nodes, sizeof(char)); //how would I know the final length?//
int i;
for (i=0; i<n; ++i) {
ListNode* head= (arr[i].head);
while (head!=NULL) { //Why do I need a tail?//
char* result;
result=whatToadd(((head->data)&(00000011)));
strcat(final, result);
free(result);
result=whatToadd(((head->data)&(00001100))>>2);
strcat(final, result);
free(result);
result =whatToadd(((head->data)&(00110000))>>4);
strcat(final,result);
free(result);
result=whatToadd(((head->data)&(11000000))>>6);
strcat(final,result);
free(result);
head=head->next;
}
}
return final;
}
int main() {
.....
free(final);
...
}
Probably, Tail has given from some reason- but (1)- can't I run on the lists the way I did? without using the tail? and if not, how should I use it?
(2)- Do I need to free result the way I did each time I get a new result from whatToAdd
?
I'm new to C, trying to work it by myself, I would really appricate tips and corrections. Thanks a lot.