I have implemented linked list data structure in c.
linkedlist.h
#ifndef LINKED_LIST
#define LINKED_LIST
#include <stdbool.h>
struct linkedlist {
int key;
struct linkedlist* next;
struct linkedlist* prev;
};
bool list_insert(struct linkedlist** p,int k);
struct linkedlist* list_search(struct linkedlist* p,int k);
bool list_delete(struct linkedlist** p,int k);
void list_show(struct linkedlist* p);
void memory_map(struct linkedlist* p);
#endif
list.c
#include "linkedlist.h"
#include <stdio.h>
#include <stdlib.h>
bool list_insert(struct linkedlist** p,int k) {
struct linkedlist* x = malloc(sizeof (struct linkedlist));
if(!x)
{
return false;
}
x->key = k;
x->prev = NULL;
x->next = *p;
if(*p)
{
(*p)->prev = x;
}
*p = x;
return true;
}
struct linkedlist* list_search(struct linkedlist* p,int k) {
if(!p)
{
return NULL;
}
while(p != NULL)
{
if(p->key == k)
{
return p;
}
p = p->next;
}
return NULL;
}
bool list_delete(struct linkedlist** p,int k) {
struct linkedlist* x = list_search(*p,k);
if(!x)
{
return false;
}
if(x->prev)
{
x->prev->next = x->next;
}
if(x->next)
{
x->next->prev = x->prev;
}
free(x);
return true;
}
void list_show(struct linkedlist* p) {
printf("\n[linkedlist][");
while(p)
{
printf("%d ",p->key);
p = p->next;
}
printf("]");
}
void memory_map(struct linkedlist* p) {
printf("\n[memory map for linkedlist]");
while(p)
{
printf("\n%d : [%p]", p->key,p);
p = p->next;
}
}
main.c
#include <stdio.h>
#include "linkedlist.h"
int main()
{
struct linkedlist* head = NULL;
int i;
for(i = 0; i < 5; i++)
{
if(!list_insert(&head,i+1))
printf("list_insert operation fails");
}
list_show(head);
memory_map(head);
list_delete(&head,2);
list_delete(&head,1);
list_delete(&head,3);
list_insert(&head,18);
list_show(head);
memory_map(head);
return 0;
}