Skip to content

Instantly share code, notes, and snippets.

@manpages
Created March 9, 2012 02:31
Show Gist options
  • Save manpages/2004681 to your computer and use it in GitHub Desktop.
Save manpages/2004681 to your computer and use it in GitHub Desktop.
Double linked list
#include <stdlib.h>
#include <stdio.h>
/**
* please put the stuff that needs to be in .h
* file in the header file. anyway, that shit
* serves educational purposes and shall not be
* used anywhere. the purpose of that shit is
* to demonstrate the concept of iterators in C99
* DELETEME: test of how does gist time line behave
*/
struct double_linked_node
{
char data;
struct double_linked_node *prev, *next;
};
struct double_linked_list
{
struct double_linked_node *first, *last;
};
struct double_linked_node dln_new_node (char arg_c)
{
struct double_linked_node new_node;
new_node.data = arg_c;
new_node.prev = new_node.next = NULL;
return new_node;
}
struct double_linked_list dln_new_list () {
struct double_linked_list new;
new.first = new.last = NULL;
return new;
}
void dln_append ( struct double_linked_node *arg_c,
struct double_linked_list *arg_list )
{
(*arg_c).next = NULL;
(*arg_c).prev = (*arg_list).last;
if ((*arg_list).last != NULL)
(*(*arg_list).last).next = arg_c;
if ((*arg_list).first == NULL)
(*arg_list).first = arg_c;
(*arg_list).last = arg_c;
}
/**
*
* Iterators :3
*
*/
// my favorite type of C99 iter
void dln_traverse_forward ( const struct double_linked_list arg_list,
void (*callback)(const struct double_linked_node *) )
{
printf("traversing double_linked_list forward\n");
struct double_linked_node *curr_node = arg_list.first;
//callback(arg_list.first);
while (curr_node != NULL){
callback(curr_node);
curr_node = (*curr_node).next;
};
//callback(arg_list.last);
return;
}
// iter to be used in for loop
struct double_linked_node *dln_fwd_first ( const struct double_linked_list l)
{
return l.first;
}
struct double_linked_node *dln_fwd_next ( const struct double_linked_node *n )
{
return (*n).next;
}
int dln_fwd_done ( const struct double_linked_node *n )
{
return n == NULL;
}
//
void dln_clb_example ( const struct double_linked_node *arg_node)
{
printf("* %c \n", (*arg_node).data);
return;
}
int main (void) {
struct double_linked_list peka = dln_new_list();
struct double_linked_node l = dln_new_node('l');
struct double_linked_node y = dln_new_node('y');
struct double_linked_node a = dln_new_node('a');
struct double_linked_node m = dln_new_node('m');
dln_append(&l, &peka);
dln_append(&y, &peka);
dln_append(&a, &peka);
dln_append(&m, &peka);
// foreach iterator
dln_traverse_forward(peka, dln_clb_example);
// first/next/done iterator
for
(
struct double_linked_node* i = dln_fwd_first(peka);
!(dln_fwd_done(i));
i = dln_fwd_next(i)
)
{
printf("** %c \n", (*i).data);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment