Tuesday, July 28, 2009

An example of abstract data type using queues in C programming?

#ifndef QUEUE_H_


#define QUEUE_H_


File: queue.h


typdef item_t int;


struct Queue {


item_t contents;


Queue* next;


};





/* Public Interface */


/* Adds a new item to the end of the queue */


void enqueue(item_t datum, Queue* head);


/* Removes the head of the queue. */


Queue* dequeue( Queue* head );


/* Returns the element at the top of the queue */


item_t* top(Queue* head);


#endif


--------





File: Queue.c





void enqueue(item_t datum, Queue* current){


if (current == NULL){


current = malloc(sizeof(Queue));


current-%26gt;contents = dataum;


current-%26gt;next = NULL;


return;


}


while (current-%26gt;next != NULL){


current = current-%26gt;next;


}


current-%26gt;next = malloc(sizeof(Queue));


current-%26gt;next-%26gt;contents = datum;


current-%26gt;next-%26gt;next = NULL;


return;


}


Queue* dequeue(Queue* head){


if (head == NULL){ return head;}


Queue* trash = head;


head = head-%26gt;next;


free(trash);


trash = NULL;


return head;


}





item_t* top(Queue* head){


if (head == NULL){ return NULL; }


else {


return %26amp;head-%26gt;contents;


}


}


No comments:

Post a Comment