Skip to content

Instantly share code, notes, and snippets.

@ruanchao
Created June 26, 2012 06:24
Show Gist options
  • Save ruanchao/2993725 to your computer and use it in GitHub Desktop.
Save ruanchao/2993725 to your computer and use it in GitHub Desktop.
Link list - C
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct node_t
{
int value;
struct node_t *next;
}node_t;
typedef struct
{
int count;
struct node_t *head;
int (*cmpfunc)(int,int);
}list_t;
list_t* list_create(int (*cmpf)(int,int));
void list_insert(list_t* plist, int num);
void list_display(list_t* plist);
int list_find(list_t* plist,int num);
void list_free(list_t* plist);
list_t*
list_create(int (*cmpf)(int,int))
{
/*
* initialise the list data structure. Check the simple.c file how
* list_t is initialised. Why do we have to do this?
*/
list_t* plist =(list_t*) malloc(sizeof(list_t));
if (!plist)
{
fprintf(stderr, "Memory allocation failed!!\n");
exit(EXIT_FAILURE);
}
plist->count = 0;
plist->head = NULL;
plist->cmpfunc =cmpf;
return plist;
}
void
list_insert(list_t* plist, int num)
{
/* any required local vars go here */
node_t *new, *current, *previous;
assert(plist != NULL );
/*
* allocate memory for a new list element and return FAILURE if
* malloc() failed.
*/
if ((new = malloc(sizeof(node_t)))== NULL){
fprintf(stderr, "Memory allocation failed!!\n");
exit(EXIT_FAILURE);
}
current = plist->head;
previous = NULL;
while(current != NULL && plist->cmpfunc(current->value,num) > 0 ){
previous = current;
current = current->next;
}
new->value = num;
new->next = current;
plist->count++;
if (previous == NULL)
{
plist->head = new;
}
else{
previous->next = new;
}
/* use function pointer stored in plist to compare elements */
}
void
list_display(list_t* plist)
{
/* any required local vars go here */
node_t* current;
assert(plist !=NULL);
/*
* loop through all existing elements
*/
current = plist->head;
printf("List has %d elements\n", plist->count);
while(current != NULL){
printf("%s\n", current->value);
current = current->next;
}
}
int
list_find(list_t* plist,int num)
{
/* any required local vars go here */
node_t *current;
assert(plist !=NULL);
/*
* loop through all existing elements.
*/
current = plist->head;
while(current != NULL && plist->cmpfunc(current->value,num)>0){
current = current->next;
}
if (current &&plist->cmpfunc(current->value,num)==0)
{
return 1;
}
else{
return 0;
}
/* return 1 on success and 0 on failure. */
}
void
list_free(list_t* plist)
{
node_t *current,*next;
assert(plist != NULL);
/*
* Need to systematically link through the free()ing the memory used
* by nodes, but not before copying any required information out of
* the node. eg. pointer to next node. so that we can continue to
* free the list
*/
current = plist->head;
while(current !=NULL){
next = current->next;
free(current);
current = next;
}
free(plist);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment