C binary search tree with custom data - c

Suppose I got an external library bst that handles custom data types insertion in a bst
Here are the new_node,insert and search functions :
//new node
struct bst_node* new_node(void* data)
{
struct bst_node* result = malloc(sizeof(struct bst_node));
assert(result);
result->data = data;
result->left = result->right = NULL;
return result;
}
//insert node
void insert(struct bst_node** root, void* data) {
struct bst_node** node = search(root, data);
if (*node == NULL) {
*node = new_node(data);
}
}
//search node
struct bst_node** search(struct bst_node** root, void* data) {
struct bst_node** node = root;
while (*node != NULL) {
if (data, (*node)->data < 0)
node = &(*node)->left;
else if (compare_result > 0)
node = &(*node)->right;
else
break;
}
return node;
}
and the main.c ,suppose i read the models from a txt file :
#include <stdio.h>
#include <stdlib.h>
#include "bst.h"
#include <string.h>
#define MAX 50
typedef struct data_t{
int gg,mm,aaaa;
}data;
typedef struct accesories_t{
char name[MAX];
int price;
struct accesories_t *next;
}accesories;
typedef struct model_t{
//int index;
char name[MAX];
char file_a[MAX];
data date;
int price;
accesories *acs;
}model;
int main(int argc, char *argv[])
{
int menu=0;
char nf[MAX];
char name[MAX];
char fa[MAX];
int price,gg,mm,a;
strcpy(nf,argv[1]);
FILE *fp=fopen(nf,"+r");
model m;
struct bst_node* root = NULL;
while(fscanf(fp,"%s %d//%d//%d %d %s",name,gg,mm,a,price,fa)!=EOF){
strcpy(m.name,name);
strcpy(m.file_a,fa);
m.date.gg=gg;
m.date.mm=mm;
m.date.aaaa=a;
m.price=price;
m.index=index++;
insert(&root ,m);
}
system("PAUSE");
return 0;
}
So my question arises in the search function, how can i manage a comparator on custom data (let's say insert the models ordered by name (strcmp) ?
I'm very confused on how can i pass the names to the bst.c given that bst.c has no idea how my model struct is made.
Should I modify the bst library and maybe on bst struct add before data some sort of index and use that as comparator ?
OK I've managed to fix that by adding a string key inside the struct bst
What I'm trying to achieve now is to return the void* data type casted into struct model,
suppose _I got the tree with nodes containing the data, once I do a search I'd like to return for
example the data contained in a node and work on it, any clues ????
tried someting like without any success
suppose node is a returned node from a search function
model *m;
m=(model*)node->data;
how could I achieve this?

Example for using compare functions as callbacks. Definitions omitted for brevity.
int llist_cmp(struct llist *l, struct llist *r)
{
if (!l) return 1;
if (!r) return -1;
return strcmp(l->payload,r->payload);
}
struct llist * llist_split(struct llist **hnd, int (*cmp)(struct llist *l, struct llist *r) )
{
struct llist *this, *save, **tail;
for (save=NULL, tail = &save; this = *hnd; ) {
if (! this->next) break;
if ( cmp( this, this->next) <= 0) { hnd = &this->next; continue; }
*tail = this->next;
this->next = this->next->next;
tail = &(*tail)->next;
*tail = NULL;
}
return save;
}
struct llist * llist_merge(struct llist *one, struct llist *two, int (*cmp)(struct llist *l, struct llist *r) )
{
struct llist *result, **tail;
for (result=NULL, tail = &result; one && two; tail = &(*tail)->next ) {
if (cmp(one,two) <=0) { *tail = one; one=one->next; }
else { *tail = two; two=two->next; }
}
*tail = one ? one: two;
return result;
}
BTW: the above snippet handles linked lists, but the mechanism for passing function pointers is the same as with trees, of course. And after all it was homework ;-)

Related

Creating and Merging Linked Lists in C programming

We are given the main function and structures, asked to create two different linked lists. One being in ascending order and another in descending order and then joined together without changing their order. To give an example,if we have L1: 1->3->4->6 and L2: 9->8->5->2, The final list would be 1->9->3->8->4->5->6->2. This below is my work. I'm having some problems.
This is the main function:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "function.h"
struct nodeFB *startFB = NULL;
struct nodeGS *startGS = NULL;
struct newNodeFB *startNewFB = NULL;
int main()
{
int id, age;
scanf("%d", &id);
while(id!=-1)
{
scanf("%d", &age);
insertFB(&startFB, id, age);
scanf("%d", &id);
}
scanf("%d", &id);
while(id!=-1)
{
insertGS(&startGS, id);
scanf("%d", &id);
}
printFB(startFB);
printGS(startGS);
createFinalList(&startNewFB,startFB,startGS);
printAll(startNewFB);
return 0;
}
These are the given structures and the functions I've written:
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
struct nodeFB
{
int id;
int age;
struct nodeFB *next;
};
struct nodeGS
{
int id;
struct nodeGS *next;
};
struct newNodeFB
{
int id;
int age;
struct newNodeGS *next;
};
struct newNodeGS
{
int id;
struct newNodeFB *next;
};
struct nodeFB *startFB;
struct nodeGS *startGS;
//functions
struct nodeFB *insertFB( struct nodeFB **startFB, int id, int age)
{//address of the first node in the linked list of FB
struct nodeFB *newnode, *ptr;
newnode = (struct nodeFB*)malloc(sizeof(struct nodeFB));
newnode->id = id;
newnode->age = age;
if (startFB == NULL) {
newnode->next = NULL;
*startFB = newnode;
}
else {
ptr = *startFB;
while(ptr->next!=NULL) {
ptr=ptr->next;
ptr->next= newnode;
newnode->next = NULL;
}
}
return *startFB;
}
void swap(struct nodeFB *a, struct nodeFB *b) {//function to swap two nodes
int temp = a->id;
a->id = b->id;
b->id = temp;
}
void sortFB(struct nodeFB *startFB) { //function to bubble sort the given linked list
int i;
int swapped;
struct nodeFB *ptr1;
struct nodeFB *ptr2= NULL;
if (startFB==NULL) { //checking for empty list
return; }
do {
swapped = 0;
ptr1=startFB;
while (ptr1->next !=ptr2) {
if (ptr1->id > ptr1->next->id) {
swap (ptr1, ptr1->next);
swapped = 1;
}
ptr1= ptr2->next;
}
ptr2=ptr1;
}
while (swapped);
}
void printFB(struct nodeFB *startFB) { //function to display the sorted list
struct nodeFB *ptr;
ptr = startFB;
sortFB(ptr);
while(ptr != NULL) {
printf("%d %d/n", ptr->id, ptr->age);
ptr=ptr->next;
}
}
struct nodeGS *insertGS(struct nodeGS **startGS, int id ) {
struct nodeGS *newnode, *ptr;
newnode = (struct nodeGS*)malloc(sizeof(struct nodeGS));
newnode->id = id;
if (startGS == NULL) {
newnode->next = NULL;
*startGS = newnode;
}
else {
ptr = *startGS;
while(ptr->next!=NULL) {
ptr=ptr->next;
ptr->next= newnode;
newnode->next = NULL;
}
}
return *startGS;
}
void swapGS(struct nodeGS *c, struct nodeGS *d) {//function to swap two nodes
int temp = c->id;
c->id = d->id;
d->id = temp;
}
void sortGS(struct nodeGS *startGS) { //function to bubble sort the given linked list
int i;
int swapped;
struct nodeGS *ptr1;
struct nodeGS *ptr2= NULL;
if (startGS==NULL) { //checking for empty list
return; }
do {
swapped = 0;
ptr1=startGS;
while (ptr1->next !=ptr2) {
if (ptr1->id < ptr1->next->id) {
swapGS (ptr1, ptr1->next);
swapped = 1;
}
ptr1= ptr2->next;
}
ptr2=ptr1;
}
while (swapped);
}
void printGS(struct nodeGS *startGS) {
struct nodeGS *ptr;
ptr = startGS;
sortGS(startGS);
while(ptr != NULL) {
printf("%d/n", ptr->id);
ptr = ptr->next;
}
}
**struct newNodeFB *createFinalList(struct newNodeFB **startNewFB, struct nodeFB *startFB, struct nodeGS *startGS ) {
struct newNodeFB *temp1, *ptr1;
temp1=(struct newNodeFB*) malloc(sizeof(struct newNodeFB));
temp1->id= startFB->id;
temp1->age=startFB->age;
struct newNodeGS *temp2;
temp2->id= startGS->id;
struct newNodeFB *temp3 = NULL;
struct newNodeGS *temp4 = NULL;
while (temp1 != NULL && temp2 != NULL)
{
ptr1=temp1;
while (ptr1->next!=NULL) {
ptr1=ptr1->next;
ptr1->next= temp2;
temp2->next=NULL;
}
temp3=temp1->next;
temp4= temp2->next;
temp1->next=temp2;
temp2->next=temp3;
temp1=temp3;
temp2=temp4;
}
startGS = temp2;
return startNewFB;
}**
void printALL(struct newNodeFB *startNewFB){
struct newNodeFB *ptr;
ptr= startNewFB;
while(ptr != NULL) {
printf("%d %d/n%d", startNewFB->id, startNewFB->age, startNewFB->id);
ptr=ptr->next;
}
}
The simplest way to create a merged list where the nodes alternate, is to simply iterate over both lists simultaneously and add each node from the two lists into a brand new list.
Because you want to alternate between the two lists, you need to use a single loop to iterate the lists, adding one node from the first list to the new merge-list, then adding one node from the second list. Stop when both lists are finished.
In pseudoish code it could look something like this:
Node *node1 = list1->head; // Node from first list
Node *node2 = list2->head; // Node from second list
// Loop while there are nodes in at least one of the lists
while (node1 != NULL || node2 != NULL)
{
if (node1 != NULL)
{
list_add_tail(merge_list, node1->data);
node1 = node1->next;
}
if (node2 != NULL)
{
list_add_tail(merge_list, node2->data);
node2 = node2->next;
}
}
As seen it's basically the same as iterating over a single list, copying data to a new list.
Another consideration is if one is mixing struct nodeFB and struct nodeGS in one list, how could the programme tell if the node is an FB or GS? Unless the lists are of equal sizes, where they are alternating, one loses type information by mixing them together.
There are several ways to get around this. One could only allow one type of node in one list; one has to convert the types to mix the lists. One might as well convert on input and have one type of list. A more nuanced approach is to store a pointer telling what type it is with every node.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/* Circular definitions mean one has to forward declare. */
struct node;
static void foo_print(const struct node *);
static void bar_print(const struct node *);
/* Virtual table stores the type of node. */
typedef void (*print_fn)(const struct node *);
static const struct vt { print_fn print; }
foo_vt = { &foo_print }, bar_vt = { &bar_print };
/* A list of nodes. */
struct node { struct node *next; const struct vt *vt; };
struct list { struct node *head; };
/* Subclasses of node. */
struct foo_node {
struct node base;
int id, age;
};
struct bar_node {
struct node base;
int id;
};
/* Implementations of the above. */
static void foo_print(const struct node *node) {
const struct foo_node *ptr = (const struct foo_node *)node;
printf("(foo)%d age %d", ptr->id, ptr->age);
}
static void bar_print(const struct node *node) {
const struct bar_node *ptr = (const struct bar_node *)node;
printf("(bar)%d", ptr->id);
}
static struct node *foo_input(void) {
int id, age;
struct foo_node *foo;
if((printf("Id: "), scanf(" %d", &id) != 1) || id == -1
|| (printf("Age: "), scanf(" %d", &age) != 1)
|| !(foo = malloc(sizeof *foo))) return 0;
foo->base.vt = &foo_vt;
foo->id = id;
foo->age = age;
fprintf(stderr, "User entered %d, %d.\n", foo->id, foo->age);
return &foo->base;
}
static struct node *bar_input(void) {
int id;
struct bar_node *bar;
if((printf("Id: "), scanf(" %d", &id) != 1) || id == -1
|| !(bar = malloc(sizeof *bar))) return 0;
bar->base.vt = &bar_vt;
bar->id = id;
fprintf(stderr, "User entered %d.\n", bar->id);
return &bar->base;
}
//address of the first node in the linked list
static void push(struct list *start, struct node *node) {
assert(start && node);
node->next = start->head, start->head = node;
}
static void printAll(const struct list *list) {
struct node *node;
for(node = list->head; node; node = node->next)
printf("%s", node == list->head ? "" : ", "), node->vt->print(node);
printf(".\n");
}
/** Interleaves the list `bars` with the list `foos`. `bars` will be the empty
list and `foos` will have all of the elements. */
static void createFinalList(struct list *foos, struct list *bars) {
/* Create this function. */
(void)foos, (void)bars;
}
int main(void) {
struct list foos = { 0 }, bars = { 0 };
struct node *node;
while(node = foo_input()) push(&foos, node);
while(node = bar_input()) push(&bars, node);
printf("foos: "), printAll(&foos);
printf("bars: "), printAll(&bars);
createFinalList(&foos, &bars);
printf("now,\n");
printf("foos: "), printAll(&foos);
printf("bars: "), printAll(&bars);
/* fixme: Memory leak, clean up. */
return 0;
}
If one really cannot modify the nodes, maybe encompass them in a union?
struct node {
const struct vt *vt;
union { struct nodeFB fb; struct nodeGS gs; };
};

recursively call in c to create link list

I am new in c so any help will be appreciated. I need to print 10 numbers from a linked list (it doesnt matter which numbers for now) I believe my code will print 9,8,7...0. for example. The linked list will be part of a struct (struct data) that will contain other variables (not important for now)
//linked list
struct listOfNodes {
struct node *root;
};
//list of parameters to send to the function to print nodes
struct data {
struct listOfNodes *list;
int total;
};
I need to send the struct (struct data) as a parameter of a recursive function (addNode). In this recursive function, I need to add a new node to the linked list and call recursively 10 times to create more nodes for the link list, then I need to print the linked list. I have the following code so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//node
struct node {
int value;
struct node *next;
};
//linked list
struct listOfNodes {
struct node *root;
};
//list of parameters to send to the function to print nodes
struct data {
struct listOfNodes *list;
int total;
};
void printNode(struct listOfNodes *list) {
struct node *n = list->root;
while(n!=NULL){
printf("%d\n",n->value);
n=n->next;
}
}
void addNode(void* d){ //parameter needs to be a void*
struct data *o = (struct data *)d ;
if(o->total<10) {
//create new node
struct node *n = malloc(sizeof(struct node));
n->value = o->total;
n->next = NULL;
o->total = o->total + 1;
if(o->list->root == NULL)
{
o->list->root = n;
}
else {
n->next = o->list->root->next;
o->list->root->next = n;
}
addNode(d);
}
}
int main() {
struct data *d= malloc(sizeof(struct data *));
d->total=0;
d->list=NULL;
addNode(d); //add recursively 10 times
if(d->list!=NULL) printNode(d->list);
return 0;
}
But I am getting Segmentation fault (core dumped). Can you please help me?
In your main program, you added list as NULL. But in your addNode, you only check if list->root is NULL. What's happening is when
if(o->list->root == NULL)
{
o->list->root = n;
}
is accessing list->root when list is NULL. You de reference a NULL pointer and segfault.
You probably need
struct listOfNodes *variable=malloc(sizeof(struct listOfNodes));
d->list=variable;
Changes are describe in comments
#include <stdio.h>
// #include <string.h> // <------- 4 not needed.
#include <stdlib.h>
struct node {//node
int value;
struct node *next;
};
struct listOfNodes {//linked list
struct node *root;
};
struct data {//list of parameters to send to the function to print nodes
struct listOfNodes *list;
int total;
};
void printNode(struct listOfNodes *list) {
struct node *n = list->root;
while(n!=NULL){
printf("%d\n",n->value);
n=n->next;
}
}
void addNode(struct data * d){ // <------- 3 no need to be void * so o replaced by d
if(d->total<10) {
//create new node
struct node *n = malloc(sizeof(struct node));
n->value = d->total;
n->next = NULL;
d->total = d->total + 1;
if(d->list->root == NULL)
{
d->list->root = n;
}
else {
n->next = d->list->root->next;
d->list->root->next = n;
}
addNode(d);
}
}
int main() {
struct data *d= malloc(sizeof(struct data)); // <---- 1 allocate data size not pointer size.
d->total=0;
d->list = malloc(sizeof(struct listOfNodes)); // <---- 2 alocate list !
d->list->root = NULL; // <---- 2 init root.
addNode(d); //add recursively 10 times
if(d->list!=NULL) printNode(d->list);
return 0;
}

Doubly linked list not working

I am trying to sort a doubly linked list in ascending order. I've gone trough the code again and again, and I can't find any logical flaws with it, so I assume the problem is elsewhere. When I try to print the sorted list, the console returns 0 without printing anything (the print function is not to blame, since it has already been tested)
Here is the code I am currrently running:
typedef struct dados_temp{
float temp;
float incerteza;
char pais[100];
char cidade[100];
float angle;
int hemisferio;
int dia;
int mes;
int ano;
} dados_temp;
typedef struct Node{
dados_temp payload;
struct Node *next;
struct Node *prev;
} Node;
//receives the original head pointer
//returns sorted list's head pointer
Node** SortDate(struct Node** head)
{
struct Node *i, *j;
for( i = head; i != NULL; i = i->next )//iterates over the entire list
{
//if the data value of the next node is bigger
if ( i->payload.ano > i->next->payload.ano )
{
//swaps the data value between i and i->next
//SwapNodes was tested and it is working
SwapNodes(i, i->next);
//the current value of i->next (former value of i)
//is compared to all the previous values
//and keeps swapping until a smaller value is found
for (j = i->next; j->payload.ano < j->prev->payload.ano;)
{
SwapNodes(j, j->prev);
}
}
}
return head;
}//sort
I know there probably are easier ways to sort doubly linked list, but I'm trying to figure out why this one doesn't work.
Thank you in advance!
EDIT:
showing all the involved functions:
#include <stdio.h>
#include <stdlib.h>
typedef struct dados_temp{
float temp;
float incerteza;
char pais[100];
char cidade[100];
float angle;
int hemisferio;
int dia;
int mes;
int ano;
} dados_temp;
typedef struct Node{
dados_temp payload;
struct Node *next;
struct Node *prev;
} Node;
Node * CreateCitiesList();
Node * CreateCountriesList();
Node * Intervalos(struct Node*, int[]);
void PrintBack(struct Node*);
struct Node* CreateNode (dados_temp x)
{
struct Node* NewNode = (struct Node*)malloc(sizeof(struct Node));
NewNode->payload = x;
NewNode->next = NULL;
NewNode->prev = NULL;
return NewNode;
}
}
void Print (struct Node* head)
{
struct Node* temp = head;
while ( temp != NULL)
{
printf("%d-%d-%d \n", temp->payload.ano, temp->payload.mes,
temp>payload.dia);
fflush(stdout);
temp = temp->next;
}
printf("\n");
}
Node* SortDate (struct Node*);
void SwapNodes (struct Node*, struct Node*);
int main(int argc, char* argv[])
{
CreateCountriesList();
}
Node* CreateCountriesList()
{
char linha[150] = {NULL};
char cabecalho[100] = {NULL};
int i = 0;
dados_temp New_Entry;
dados_temp tail;
int *ptr_head_co;
struct Node* head_countries = NULL;
struct Node* Node = NULL;
FILE *inputf;
inputf = fopen("tempcountries_all.csv", "r");
if (inputf == NULL)
{
printf("Nao da pa abrir o fitchas boi");
exit(EXIT_FAILURE);
}
//gets rid of the first line
fgets(cabecalho, 100, inputf);
for (i = 0; i < 577462 ; i++)
{
fgets(linha, 150, inputf);
//scans the date(amongst other things) from file (yyyy-mm-dd)
sscanf(linha, "%d-%d-%d,%f,%f,%[^,]s", &New_Entry.ano,
&New_Entry.mes,&New_Entry.dia, &New_Entry.temp, &New_Entry.incerteza,
&New_Entry.pais);
if (head_countries == NULL)
{
head_countries = CreateNode(New_Entry);
Node = CreateNode(New_Entry);
}
else
{
head_countries = InsertHead(head_countries, New_Entry);
}
}
fclose(inputf);
head_countries = RemoveNodes(Node);
SortDate(head_countries);
Print(head_countries);
return head_countries;
}
Node* SortDate(struct Node* head)
{
struct Node *i, *j;
for( i = head; i != NULL; i = i->next )
{
if ( i->payload.ano > i->next->payload.ano )
{
SwapNodes(i, i->next);
for (j = i->next; j->payload.ano < j->prev->payload.ano;)
{
SwapNodes(j, j->prev);
}
}
}
}//sort
void SwapNodes(struct Node* node1, struct Node* node2)
{
dados_temp temp = node1->payload;
node1->payload = node2->payload;
node2->payload = temp;
}

Generic linked list?

I was wondering if that was possible to use generic function for linked lists in C, (i don't want to do that in C++ but in C) example :
struct first_struct
{
struct first_struct *next;
int a;
int b;
};
struct second_struct
{
struct second_struct *next;
int a;
int b;
int c; // just one more variable than first-struct
};
am i force to make a function each time for the two lists :
add_node(struct first_struct *mystruct)// doesn't matter the function here juste let's assume they add correctly a node
add_node1(struct second_struct *mystruct)
//and so on each time i want to make some others function always make them twice
or is there a better way to do that ?
The better way is to abstract out the link handling (what makes a structure into a list node) and then re-use that by starting each listable structure with the node structure.
Like so:
struct list_node {
struct list_node *next;
};
struct first_struct {
struct list_node list_node;
int a;
int b;
};
struct second_struct {
struct list_node list_node;
int a;
int b;
int c;
};
Then make list functions that deal with (pointers to) struct list_node.
This is commonly called "intrusive lists", since it requires the application-level data structure to "know" that it's possible to put it in a list. It also means an instance of a structure can only be on one list at a time.
The other way is to make a list library that only deals with pointers to data (void *), that removes the limitation but brings others instead (more heap allocation, annoying when data is small).
Personally, I have implemented a generic linked list : it work by providing a function to compare two node, and an optional function to destroy a node (free string, close file, etc etc).
#include <stdbool.h>
#include <stddef.h>
typedef struct link {
void *data;
struct link *previous;
struct link *next;
} link_s;
typedef struct list {
link_s *head;
link_s *tail;
size_t nbLink;
/* function pointer */
int (*Data_Compare)(const void *data1, const void *data2);
void (*Data_Destructor)(void *data);
} list_s;
#define LIST_CONSTRUCTOR(f_compar, f_destructor) {.head = NULL, \
.tail = NULL, \
.nbLink = 0, \
.Data_Compare = f_compar, \
.Data_Destructor = f_destructor}
void List_Constructor(list_s *self, int (*Data_Compare)(const void *data1, const void *data2), void (*Data_Destructor)(void *data));
void List_Destructor(list_s *self);
bool List_Add(list_s *self, void *data);
void *List_RemoveByLink(list_s *self, link_s *link);
void *List_RemoveByData(list_s *self, void *data);
void *List_RemoveByCondition(list_s *self, bool (*Data_Condition)(const void *data));
void List_DestroyByLink(list_s *self, link_s *link);
void List_DestroyByData(list_s *self, void *data);
void List_DestroyByCondition(list_s *self, bool (*Data_Condition)(const void *data));
void List_Sort(list_s *self);
void List_Merge(list_s *to, list_s *from);
void List_Reverse(list_s *self);
This way, you can add whatever you want into the list. Just be carefull to have a propre comparison function and destroy function.
You can implement a generic linked list fairly easy using a void pointer in your struct.
Here is an example of a such list created by me:
list.c
#include <stdlib.h>
#include "list.h"
#include <malloc.h>
#include <stdio.h>
#include <string.h>
void listNew(list* list, unsigned int elementSize, freeMemory freeFn,
printList print) {
list->numOfElem = 0;
list->freeFn = freeFn;
list->pr = print;
list->head = NULL;
list->sizeOfElem = elementSize;
}
node * listPushFront(list *list, void* data) {
node *listNode = (node*)malloc(sizeof(node));
if (listNode == NULL) {
return NULL;
}
listNode->object = malloc(sizeof(list->sizeOfElem));
if (listNode->object == NULL) {
return NULL;
}
memcpy(listNode->object, data, list->sizeOfElem);
listNode->pNext = list->head;
list->head = listNode;
list->numOfElem++;
return listNode;
}
void listDestroy(list *list)
{
node *current;
while (list->head != NULL) {
current = list->head;
list->head = current->pNext;
if (list->freeFn) {
list->freeFn(current->object);
}
free(current->object);
free(current);
}
}
void listPrint(list *l) {
node* temp = l->head;
int i = 0;
if (temp == NULL) {
printf("\nEmpty list.");
return;
}
while (temp) {
printf("\nPrint element %d", i);
l->pr(temp->object);
temp = temp->pNext;
i++;
}
}
list.h
#ifndef __LIST_H
#define __LIST_H
typedef void(*freeMemory)(void*);
typedef void(*printList)(void*);
typedef struct _node {
void* object;
struct _node* pNext;
}node;
typedef struct _list {
unsigned int sizeOfElem;
unsigned int numOfElem;
node* head;
freeMemory freeFn;
printList pr;
}list;
void listNew(list* list, unsigned int elementSize, freeMemory freeFn,
printList print);
node * listPushFront(list *list, void* data);
void listDestroy(list *list);
void listPrint(list *l);
#endif
main.c
#include <stdlib.h>
#include "list.h"
#include <stdio.h>
#include <string.h>
typedef struct _TLV {
unsigned int tag;
unsigned int length;
unsigned char* value;
}TLV;
void listFree(void* data) {
TLV** ptr = (TLV**)data;
free((*ptr)->value);
}
void Print(void* data) {
TLV** ptr = (TLV**)data;
printf("\nTag = %d", (*ptr)->tag);
printf("\nLength = %d", (*ptr)->length);
printf("\nValue = ");
for (int i = 0; i < (*ptr)->length; i++) {
printf("%d", (*ptr)->value[i]);
}
}
TLV* allocateTLV(unsigned int tag, unsigned int length, unsigned char*
value) {
TLV* elem = (TLV*)malloc(sizeof(TLV));
if (elem == NULL) {
return NULL;
}
elem->tag = tag;
elem->length = length;
elem->value = (unsigned char*)malloc(length);
if (value == NULL) {
return NULL;
}
memcpy(elem->value, value, length);
return elem;
}
int main()
{
list l;
TLV* tag;
unsigned char test2[2] = { 1,2 };
unsigned char test3[3] = { 1,2,3 };
unsigned char test4[4] = { 1,2,3,4};
listNew(&l, sizeof(TLV*), listFree, Print);
tag = allocateTLV(2, sizeof(test2), test2);
if (tag != NULL) {
listPushFront(&l, &tag);
}
tag = allocateTLV(3, sizeof(test3), test3);
if (tag != NULL) {
listPushFront(&l, &tag);
}
tag = allocateTLV(4, sizeof(test4), test4);
if (tag != NULL) {
listPushFront(&l, &tag);
}
listPrint(&l);
listDestroy(&l);
return 0;
}
main.c is an example of creating a list of pointers to the struct TLV.
You could implement a generic linked list by using two features of C, namely void pointers and function pointers.
The latter (function pointers) is not crucial for building the linked list, but it is crucial if you want to do something useful with the data of the linked list such as printing.
Here is a full working example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
void *data;
struct node *next;
} node;
int lst_nodeAdd(
node **head,
node **tail,
const void *data,
size_t szData);
void lst_nodePrint(
node *head,
void(*print)(const void *));
void lst_nodeFree(node *head);
/* PRINTING FUNCTIONS */
void print_int(const void *a);
void print_string(const void *str);
int main(void)
{
const char *str[] = {
"0x0001",
"0x0002",
"0x0003",
};
// head & tail
node *head = NULL;
node *tail = NULL;
// List of strings
lst_nodeAdd(&head, &tail, str[0], strlen(str[0]) + 1);
lst_nodeAdd(&head, &tail, str[1], strlen(str[1]) + 1);
lst_nodeAdd(&head, &tail, str[2], strlen(str[2]) + 1);
lst_nodePrint(head, print_string);
lst_nodeFree(head);
head = NULL;
tail = NULL;
//....................................................
// List of ints
int int_array[] = {
0,
1,
2,
};
lst_nodeAdd(&head, &tail, &int_array[0], sizeof(int));
lst_nodeAdd(&head, &tail, &int_array[1], sizeof(int));
lst_nodeAdd(&head, &tail, &int_array[2], sizeof(int));
lst_nodePrint(head, print_int);
lst_nodeFree(head);
head = NULL;
tail = NULL;
system("PAUSE");
return 0;
}
int lst_nodeAdd(
node **head,
node **tail,
const void *data,
size_t szData)
{
void *tmp;
tmp = malloc(sizeof(node));
if (!tmp)
{
return 0;
}
((node *)tmp)->next = NULL;
((node *)tmp)->data = malloc(szData);
if (!((node *)tmp)->data)
{
free(tmp);
return 0;
}
memcpy(((node *)tmp)->data, data, szData);
if (!*head)
{
*head = (node *)tmp;
}
else
{
(*tail)->next = (node *)tmp;
}
*tail = (node *)tmp;
return 1;
}
void lst_nodePrint(
node *head,
void(*print)(const void *))
{
while (head)
{
print(head->data);
head = head->next;
}
}
void lst_nodeFree(node *head)
{
node *tmp = head;
while (head)
{
head = head->next;
free(tmp->data);
free(tmp);
tmp = head;
}
}
void print_int(const void *a)
{
printf("%d\n", *(const int *)a);
}
void print_string(const void *str)
{
puts((const char *)str);
}

adding to linked list generically nullptr issue

I am trying to add to a linked list generically, because i have 2 linked lists and I call the same function for the two lists.
void addToList(void* (*createNode)(void *data,char* name), int (compare)(void *a1, void *a2), void *(*getNext)(void), void(*setNext)(void *node, void* data), void *data,char* name, void **list) {
void *node = createNode(data,name);
void *head = *list;
if (head == NULL) { // if list is empty
*list = node;
}
else if (compare(head, node)) { // if first element is greater than node to add (meaning we need to add node to head of list)
setNext(node, list);
*list = node;
}
else {
// node will be inserted someplace other than head
void *current = head;
while (getNext(current) != NULL && compare(node, getNext(current))) {
// loop until we are at the end of the list OR until we have found an element greater than us
// basically, current will be the place to put the new node in
current = getNext(current);
}
setNext(node, getNext(current));
setNext(current, node);
}
Here is the struct and list and node
struct Stud {//my struct contains 2 lists
int id;
float gradeAverage;
float incomeAverage;
struct gradeList *gradelist;
struct incomeList *incomelist;
};
typedef struct Stud Students;
struct gradeNode {//the grade node with what is inside it
char courseName[20];
int grade;
struct gradeNode *next;
struct gradeNode *prev;
};
struct gradeList {//my first list with head and tail
struct gradeNode *head;
struct gradeNode *tail;
int size;
};
struct incomeNode {//my secound node
char *workplace;
float income;
struct incomeNode *next;
struct incomeNode *prev;
};
struct incomeList {//the secount list
struct incomeNode *head;
struct incomeNode *tail;
int size;
};
Here are the functions that I used
void* get_next_Income(void* head) {//used above in the generic call
return((struct incomeNode *)head)->next;
}
void* get_next_Grade(void* head) {//used above to get the income
return(((struct gradeNode *)head)->next);
}
int compareGradeNode(void *a1, void *a2) {//compares the node iam adding to the exicting node and adding accordingly
return ((struct gradeNode*)a1)->grade > ((struct gradeNode*)a2)->grade;
}
int compareIncomeNode(void *a1, void *a2) {
return ((struct incomeNode*)a1)->income>((struct incomeNode*)a2)-
>income;
}
void setNextGradeNode(void* node, void* data) {//seting the next graded
((struct gradeNode*)node)->next = data;
}
void setNextIncomeNode(void* node, void* data) {//setting the next income
((struct incomeNode*)node)->next = data;
}
Students students[30];
int numOfStuds = 0;
void* createGradeNode(void* data,char*name) {
struct gradeNode* nd=(struct GradeNode*)malloc(sizeof(struct gradeNode));
strcpy(nd->courseName, name);
assert(nd != NULL);
nd->grade = data;//setting the new node to the data the user entered!
nd->next = NULL;
return nd;//and return it
}
The problem is that I got a null ptr in the code part below.
I am using visual studio and can't solve it.
Please help.
Sorry for the long code, I am new to c.
void *head = *list;
if (head == NULL) { // if list is empty
*list = node;

Resources