Nostalgia.. Touched #C for the first time in ages

#include <stdio.h>
#include <stdlib.h>
#define MAX_ELEMENTS 4

typedef struct _node {
  int el;
  struct _node *next;
} node;

node *push(node *head, int el) {
  if (head == NULL) {
    node *first = malloc(sizeof(struct _node));
    first->el = el;
    first->next = NULL;
#ifdef DEBUG
    printf("Element [%d] added as head\n", el);
#endif
    return first;
  }
  node *curr = head;
  while ((curr->next != NULL) && (curr != NULL)) {
    curr = curr->next;
  }
  node *tmp = malloc(sizeof(struct _node));
  tmp->el = el;
  tmp->next = NULL;
  curr->next = tmp;
#ifdef DEBUG
  printf("Element [%d] added\n", el);
#endif
  return curr;
}

int pop(node **head) {
  node *curr = (*head);
  int ret = (*head)->el;
  (*head) = (*head)->next;
  free(curr);
  return ret;
}

int printList(node *head) {
  node *curr = head;
  while (curr->next != NULL) {
    printf("[%d]\t", curr->el);
    curr = curr->next;
  }
  printf("[%d]\n", curr->el);
}

void freeList(node *head) {
  node *curr = head;
  node *tmp = NULL;
  while (curr != NULL) {
    tmp = curr;
#ifdef DEBUG
    printf("Freeing element [%d] \n", tmp->el);
#endif
    curr = curr->next;
    free(tmp);
  }
}

int main() {
  node *head = push(NULL, 0);
  printList(head);
  int i;
  for (i = 1; i < MAX_ELEMENTS; i++) {
    push(head, i);
    printList(head);
  }
  printf("Starts with pop(ing)\n\n");
  int n = pop(&head);
  printf("\nPop(ed) [%d]\n\n", n);
  printList(head);
  n = pop(&head);
  printf("\nPop(ed) [%d]\n\n", n);
  printList(head);
  printf("Starts freeing \n\n");
  freeList(head);
  return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s