I am trying to improve my c programming skills and so started with trying to program a double linked list.
Here is what i have come up with so far.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
//forward definition
typedef struct Node node_t;
//Define the structures needed for double linked list
//Each node
typedef struct Node
{
int data;
node_t *next;
node_t *prev;
}node_t;
void initList(node_t** first , node_t** last)
{
//Allocate memory for the first and the last node
*first = (node_t*) malloc(sizeof(node_t));
*last = (node_t*) malloc(sizeof(node_t));
(*first)->data = 1;
(*last)->data = 2;
(*first)->prev = NULL;
(*last)->next = NULL;
(*first)->next = (*last)->prev;
return;
}
void destroyList(node_t** first)
{
node_t* temp;
temp = *first;
free((*first)->next);
free((*first));
temp = NULL;
return;
}
int main()
{
node_t *first =NULL, *last = NULL;
printf("Initalizing the List\n");
initList(&first,&last);
printf(" 1st element is %d\n",first->data);
printf(" 2nd element is %d\n",last->data);
printf("Destroying the List\n");
destroyList(&first) ;
return 0;
}
I actually looked up for some code online and i see that most implementations have
1) 1 structure for Node and 1 structure for List itself (with head and tail). My question is, is this mandatory? Can i not implement it with just 1 structure?
2) My idea is to make this file as a library and call it from an application. Like
InitList(), DestroyList(), AddNode, DeleteNode etc.
And that is why i am using double pointers for the INit and destroy. I am having some trouble destroying the list. I know i am doing it wrong, i will continue to correct it.
3) I found that node pointer
temp = first
was pointing to some address. If i do temp++. Why doesn't it point to next node?
4)We can either pass the first or the last node pointer to delete the entire list correct?. ( i.e traverse and dleete sequentialluy?)
Thanks!
(*first)->next = *last; (*last)->prev = *first;rather than(*first)->next = (*last)->prev;.