Skip to content

Instantly share code, notes, and snippets.

@ObjSal
Last active March 16, 2016 03:32
Show Gist options
  • Save ObjSal/4469c6263afb1d0dce41 to your computer and use it in GitHub Desktop.
Save ObjSal/4469c6263afb1d0dce41 to your computer and use it in GitHub Desktop.
singly-linked list
//
// List.h
// Data Structures
//
// Created by Salvador Guerrero on 3/15/16.
// Copyright © 2016 ByteApps. All rights reserved.
//
/*
* Singly-linked list
*
* A samples can be found at: https://github.com/ObjSal/Data-Structures
*/
#ifndef List_h
#define List_h
// define your own data type before including this file
#ifndef item_type
#define item_type int
#endif
struct list {
item_type item; // data
struct list *next; // pointer to successor
};
/*
* recursive search
*/
struct list* list_search(struct list *list_head, item_type item)
{
if (list_head == NULL) return NULL;
if (list_head->item == item)
{
return list_head;
}
else
{
return list_search(list_head->next, item);
}
}
/*
* insertion done at the beginning of the list instead of traversing all the list
*/
void list_insert(struct list **list_head, item_type item)
{
struct list *temp_list = (struct list *)malloc(sizeof(struct list));
temp_list->item = item;
temp_list->next = *list_head;
*list_head = temp_list;
}
/*
* find the predecessor of a given list node
*/
struct list* list_predecessor(struct list *list_head, item_type item)
{
if (list_head == NULL || list_head->next == NULL)
{
printf("Error: predecessor not found\n");
return NULL;
}
if (list_head->next->item == item)
{
return list_head;
}
else
{
return list_predecessor(list_head->next, item);
}
}
/*
* delete a node with the given item.
*/
void list_delete(struct list **list_head, item_type item)
{
struct list *item_list_p = list_search(*list_head, item);
struct list *predecessor;
if (item_list_p == NULL) return;
predecessor = list_predecessor(*list_head, item);
if (predecessor)
{
predecessor->next = item_list_p->next;
}
else
{
*list_head = item_list_p->next;
}
// free node memory
free(item_list_p);
}
/*
* prints all the items
*/
void list_description(struct list *list_head)
{
if (list_head == NULL) return;
int count = 0;
for (struct list *list = list_head; list; list = list->next)
{
printf("[%d], item = %d\n", ++count, list->item);
}
}
/*
* free all the list.
*/
void list_free(struct list *list_head)
{
if (list_head == NULL) return;
struct list *list = list_head;
for (;list;)
{
struct list *temp_list = list->next;
free(list);
list = temp_list;
}
}
#endif /* List_h */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment