Queues Flashcards
Memorizing enqueue, dequeue, and front and any specifics related to them
What is the philosophy of a queue and what can it be resembled to in real life?
Queues work in first-in, first-out and just as their name suggests, they resemble a queue in real life (FIFO)
What are the three operations that we learnt when implementing queues?
1) Front
2) Enqueue
3) Dequeue
What is an enqueue implementation look like?
void enqueue(queue_t queue, int elem) {
assert(queue != NULL);
node_t newnode = malloc(sizeof(node_t));
newnode->element = elem;
newnode->next = NULL;
if (queue->rear == NULL) {
queue->front = newnode;
} else {
queue->rear->next = newnode;
}
queue->rear = newnode;
queue->size++;
}
What about an implementation of front()?
_Bool front(queue_t *queue, int *elem) {
assert(queue != NULL && elem != NULL);
if (queue->front == NULL) {
return false;
}
*elem = queue->front->element;
return true;
}
What is an example of the implementation of dequeue()?
_Bool dequeue(queue_t *queue, int *elem) {
assert(queue != NULL && elem != NULL);
if (queue->size == 0) {
return false;
}
elem = queue->front->element;
node_t node_to_delete = queue->front;
if (queue->size == 1) {
queue->rear = NULL;
}
queue->front = queue->front->next;
free(node_to_delete);
queue->size–;
return true;
}
What would be a type of implementation that can be used to print queues?
void print_queue(queue_t queue) {
assert(queue != NULL);
if (queue->size == 0) {
printf(“{ }\n”);
return;
}
printf(“{“);
for (node_t curr = queue->front; curr != queue->rear;
curr = curr->next) {
printf(“%d, “, curr->element);
}
printf(“%d}\n”, queue->rear->element);
}
What changes for an circular linked list?
There is no actual front of the loop, the front of the loop is referred to by queue->rear->next;
What is an enqueue implementation for a circular queue?
void enqueue(queue_t *queue, int value) {
assert(queue != NULL);
node_t *newnode;
newnode = malloc(sizeof(node_t));
assert(newnode != NULL); //will ensure that malloc did not fail
newnode -> data = value;
if (queue -> rear == NULL){
newnode->next = newnode; //creates that circular link
queue->rear = newnode;
} else{ newnode->next = queue->rear->next; // queue->rear->next = newnode->next; queue->rear->next = newnode; } queue->rear = newnode; //ask ta to explain this LOL queue->size++;
}
What is a dequeue implementation for a circular linked list?
_Bool dequeue(queue_t *queue, int element) {
assert(queue != NULL && element != NULL);
if (queue->rear == NULL){ //empty queue
return false;
}
node_t to_remove = queue->rear->next;
*element = to_remove->data; //copying elem
if (queue->size == 1){
queue->rear = NULL;
} else {
queue->rear->next = to_remove->next;
}
free(to_remove);
queue->size -=1 ;
return true;
}
What is a front implementation for a circular queue?
_Bool front(const queue_t *queue, int *element) {
assert(queue != NULL && element != NULL);
if (queue->rear == NULL){
return false;
}
*element = queue->rear->next->data;
return true;
}