Skip to content

Instantly share code, notes, and snippets.

@ruanchao
Created July 3, 2012 11:30
Show Gist options
  • Save ruanchao/3039186 to your computer and use it in GitHub Desktop.
Save ruanchao/3039186 to your computer and use it in GitHub Desktop.
Doubly Linked list C
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#ifndef QUEUE_H
#define INPUT_BUFFER_SIZE 100
#define OP_QUEUE_ENQUEUE 0
#define OP_QUEUE_DEQUEUE 1
#define OP_QUEUE_END 2
typedef struct node_t {
int value;
struct node_t *next;
struct node_t *previous;
} node_t;
typedef struct {
int count;
struct node_t *front;
struct node_t *rear;
} queue_t;
void queue_init(queue_t *);
int queue_is_empty(queue_t *);
void queue_enqueue(queue_t *, int);
int queue_dequeue(queue_t *);
void queue_free(queue_t *);
#endif
void
queue_init(queue_t * pque)
{
assert(pque != NULL);
/* init queue data structure */
pque->count = 0;
pque->front = NULL;
pque->rear = NULL;
}
void
queue_enqueue(queue_t * pque, int item)
{
node_t *new;
assert(pque != NULL);
/*
* allocate memory and exit if we can't allocate anymore memory.
* Cleanup before we exit the program though
*/
if ((new = malloc(sizeof(node_t))) == NULL) {
fprintf(stderr, "Memory allocation for queue_enqueue failed! "
"Aborting data entry !\n");
queue_free(pque);
exit(EXIT_FAILURE);
}
new->value = item;
new->previous = NULL;
new->next = pque->front;
/* empty queue */
if (pque->front != NULL) {
pque->front->previous = new;
}
if (pque->rear == NULL) {
pque->rear = new;
}
/* add new item to the front */
pque->front = new;
pque->count++;
}
int
queue_dequeue(queue_t * pque)
{
node_t *last;
int val;
assert(pque != NULL);
assert(pque->count > 0);
/* remove last item and make 2nd last = rear */
last = pque->rear;
pque->rear = last->previous;
if (pque->rear)
pque->rear->next = NULL;
val = last->value;
free(last); /* free memory used by item */
pque->count--;
return val;
}
int
queue_is_empty(queue_t * pque)
{
assert(pque != NULL);
if (pque->count == 0)
return 1;
return 0;
}
void
queue_free(queue_t * pque)
{
node_t *del;
assert(pque != NULL);
/*
* remove and delete items from the back of the list till there is no
* item left
*/
while (!queue_is_empty(pque)) {
del = pque->rear;
pque->rear = del->previous;
pque->count--;
free(del);
}
pque->front = NULL;
pque->rear = NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment