All Up In Linked Lists

Yesterday I started on linked lists, and this one looks like it will go 2-3 days. I started off with a nice C implementation, with many functions for manipulating a list.

I was pretty proud, then I started looking around and the other implementations I'm seeing are different from mine. Not in correctness, because mine work perfectly - I wrote tests! The difference is my functions took the list as an argument. These other implementations take the head node as an argument instead. Really? That means the internals of your list are just hanging out in main() or wherever, or the global context (yeesh), and anyone can change the head pointer, tail pointer, etc. I feel mine is better because I encapsulate the internals.


void push(node_t * head, int val) {  
    node_t * current = head;
    while (current->next != NULL) {
        current = current->next;

    /* now we can add a new variable */
    current->next = malloc(sizeof(node_t));
    current->next->val = val;
    current->next->next = NULL;


void jforward_list_push_back(JForwardList *jlist, int value) {  
  struct SingleNode *node = malloc(sizeof(struct SingleNode));

  node->data = value;
  node->next = 0;

  if (jlist->head == 0) {
    jlist->head = node;
    jlist->tail = node;
  } else {
    jlist->tail->next = node;
    jlist->tail = node;

I'm also a big fan of functions that don't look outside their scope for dependencies. If a function needs something, just provide it as an argument, unless it's a class method, then it can have visibility to class members, as is the OO way. Some of the C methods I'm seeing are expecting head or tail from the outer scope. Eww.

Mine is a quasi-OO style. I like encapsulation. It's convenient for the user and protects the internal state.

In any case, I'm relenting so I can get some practice with this other way of managing lists. I'm pretty flexible.

So I'm starting over to implement in the common manner in C. Then I'll move to an OO version in C++, with a template for universal type-handling.

comments powered by Disqus