//queuelib.c stack library body file //PAC: jleblanc: 2.16.06 #include "queuelib.h" boolean qempty(const queuetype q) { return ((boolean) (q.top == NULL)); // we could also test the count field, but we are emphasizing pointers } boolean qfull (const queuetype q) { return FALSE; //we should check available memory first, but we'll keep it simple for now } void qmany(int *answer, queuetype *q) { *answer=q->count; } void qinit ( queuetype *q ) { q -> count = 0; q -> top = NULL; q->rear = NULL; } //ADD to rear of the list void qadd(char item, queuetype *q ) { qnode *p; if (! qfull(*q)) { p = malloc(sizeof(qnode)); // request the space, put address in p p -> info = item; // transfer the item into p's info p->next=NULL; //set new node's pointer to NULL since at the end if(q->rear != NULL) { q->rear->next=p; //set the current rear node's next to the new node (only if current rear exsists) } else { q->top=p; // if rear is NULL then there are no nodes, so top must be set to the new node } q->rear=p; //set the queue's rear to the new rear q -> count ++; // increment the 'count' field } } //REMOVE from the front of the list void qremove( char *item, queuetype *q ) { qnode *p; if (! qempty(*q)) { *item=q->top->info; //get the item info of first node p=q->top; //p points to first node q->top=p->next; //top points to the next node free(p); //delete the node q->count--; //decrement the count field if(q->top==NULL) { q->rear=NULL; //if top points to NULL then there are no nodes so rear points to NULL also } } } //Below here is the implimentation to Add to the Front, and Remove from the Rear. //As the code shows it requires a bit more work. //This code can be substituted for the 2 functions above with no difference to the user. /* void qadd ( char item, queuetype *q ) { node *p; if (! full(*q)) { p = malloc(sizeof(node)); // request the space, put address in p p -> info = item; // transfer the item into p's info p -> next = q -> top; // set p's next to the old top q -> top = p; // set new top of stack to point to p q -> count ++; // increment the 'count' field } if(q->count==1) { q->rear=q->top; } } void qremove( char *item, queuetype *q ) { node *p; if (! empty(*q)) { *item = q -> rear -> info; // transfer the info from rear of queue //Figure out how to do this more cleanly p = q -> top; // set temporary pointer p to top if(q->count == 1) { q->top=NULL; q->rear=NULL; q->count--; free(p); } else { for(int x=1; x<((q->count)-1); x++) { p=p->next; } free(p->next); //kills the last one p->next=NULL; q->rear=p; q -> count--; // decrement the count field of stack } } } */