C programming language does not provide templates which are commonly used for generic container data types in other statically typed programming languages. This feature however can be implemented in C by the use of macros.
C macros have been extensively used in implementing generic containers. This repository contains implementation of generic list in C language.
Lists are sequence containers that allow for non contiguous memory allocation.
The library provides a generic list container that is compatible with standard types as well as user defined types.
The internal implementation uses a singly linked list.
Function | Description |
---|---|
gl_init | initializes the list with user provided type |
gl_size | returns the number of elements |
gl_find | returns iterator to the element if found |
gl_push_back | adds an element to the end |
gl_pop_back | removes the last element |
gl_push_front | inserts an element to the beginning |
gl_pop_front | removes the first element |
gl_remove | removes all occurences of the given element |
gl_clear | clears the contents |
gl_sort | sorts the elements (uses merge sort) |
gl_iterator | iterator for given type |
gl_init_iterator | initialise the iterator to given list |
gl_iterator_eq | compare two iterators |
gl_begin | iterator to the beginning of container |
gl_end | iterator to one past the end of container |
#include <stdio.h>
#include "glist.h"
glist(int) intlist;
int main()
{
intlist l = gl_init(int); // []
gl_push_front(l, 4); // [4]
gl_push_back(l, 3); // [4, 3]
gl_push_back(l, 1); // [4, 3, 1]
gl_push_back(l, 2); // [4, 3, 1, 2]
gl_push_front(l, 4); // [4, 4, 3, 1, 2]
gl_remove(l, 4); // [3, 1, 2]
gl_sort(l); // [1, 2, 3]
gl_iterator(int) it;
gl_init_iterator(int, one, &it);
while(has_next(&it))
{
printf("%d ", next(&it)); // 1 2 3
}
}