#include "queue.h" #include #include #include #define DEBUG if(0) /* Queue has a dummy head and the end node points back to the head. */ //create a head, point it to itself and return a pointer to the head //of the list QUEUE Q_init(){ QNODE* n = (QNODE*)malloc(sizeof(QNODE)); assert(n); n->next = n; DEBUG{printf("Q_init %p\n",n);fflush(stdout);} return n; } // insert element e at the head of the list by copying its contents into QNODE void Q_insert_elem_head(QUEUE h, queueElem e){ assert(h && e); DEBUG{ printf("Q_insert_elem_head: %d %d %d\n",e[0],e[1],e[2]); fflush(stdout); } QNODE* n = (QNODE*)malloc(sizeof(QNODE)); assert(n); n->e[0] = e[0]; n->e[1] = e[1]; n->e[2] = e[2]; n->next = h->next; h->next = n; } // insert QNODE at head of the list void Q_insert_qnode_head(QUEUE h, QNODE* n){ assert(h && n); DEBUG{printf("Q_insert_qnode_head: %p\n",n);fflush(stdout);} n->next = h->next; h->next = n; } // remove the first element in the queue QNODE* Q_remove_first(QUEUE h){ assert(h); DEBUG{printf("Q_remove_first %p\n",h);fflush(stdout);} // If the head is first don't remove it if(Q_first(h) == NULL) return NULL; else{ QNODE* f; f = Q_first(h); assert(f); h->next = f->next; return f; } } // remove the first element and free it from memory short Q_delete_first(QUEUE h){ assert(h); DEBUG{printf("Q_delete_first\n");fflush(stdout);} // If the head is first don't remove it if(Q_first(h) == NULL) return 0; else{ QNODE* f; f = Q_first(h); assert(f); h->next = f->next; free(f); return 1; } } void Q_free_queue(QUEUE h){ assert(h); while(Q_delete_first(h)); free(h); } //returns first element after head, or NULL if queue is empty (dummy only) QNODE* Q_first(QUEUE h){ assert(h); return (h->next == h)? NULL: h->next; } //returns p->next QNODE* Q_next(QUEUE h, QNODE* p){ assert(h && p); return (p->next == h)? NULL: p->next; } //returns 1 if p is the last element in the queue else 0 short Q_isEnd(QUEUE h, QNODE* p){ assert(h && p); return (p->next == h); } /* //tricky --- this will actually delete p->next */ /* short Q_delete(QNODE* p){ */ /* assert(p); */ /* // If p is the end the don't delete anything */ /* if(Q_isEnd(Q_next(p))) */ /* return 0; */ /* // Otherwise remove p->next */ /* else{ */ /* QNODE* tmp; */ /* tmp = p->next; */ /* p->next = p->next->next; */ /* free(tmp); */ /* return 1; */ /* } */ /* } */