#Function creation - Datastructures - Linked Queue

11 messages · Page 1 of 1 (latest)

quasi marsh
#

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "printer.h"
#include "queue.h"
#include "task.h"

int main()
{
    srand(time(NULL));
    struct printer *p = malloc(sizeof(struct printer));
    struct queue *q = create_queue();
    struct task *t = create_task(0);
    tick(p);
    is_busy(p);
    enqueue(q, t);
    start_next(p, t);
    free(q);
    free(t);
}

struct queue *create_queue()
{
    struct queue *myqueue = malloc(sizeof(struct queue));
    myqueue->front = NULL;
    myqueue->rear = NULL;
    return myqueue;
}

struct task *create_task(int ct)
{
    struct task *newtask = malloc(sizeof(struct task));
    newtask->pages = rand();
    newtask->time_stamp = ct;
    return newtask;
}

void enqueue(struct queue *q, struct task *t)
{
    struct node *ptr = malloc(sizeof(struct node));
    ptr->data = t;
    if (q->front == NULL)
    {
        q->front = ptr;
        q->rear = ptr;
    }
}

void tick(struct printer *p)
{
    p->time_remaining = p->time_remaining - 1;
}

int is_busy(struct printer *p)
{
    if (p->time_remaining > 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
struct task *dequeue(struct queue *q)
{
    if (q->front == NULL)
    {
        printf("Queue is empty.\n");
    }
    struct node *dequeuedNode = q->front;
    struct task *dequeuedTask = dequeuedNode->data;
    q->front = q->front->next;

    free(dequeuedNode);

    return dequeuedTask;
}
void start_next(struct printer *p, struct task *t)
{

}
void printer_status(struct printer *p);

int is_empty(struct queue *q);```
fervent adderBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

quasi marsh
#

Hi, i need some help in creating the struct task *dequeue(struct queue *q) function

#

How do i return a task that is within a node which is inside a queue?

spark patrol
#

What's wrong with your solution?

quasi marsh
#

It was empty when i posted it here but i decided to gpt it while i waited. Not sure if it works tho

#
int main()
{
    srand(time(NULL));
    int options = 0;
    struct printer *p = malloc(sizeof(struct printer));
    struct queue *q = create_queue();

    while (scanf("%d", &options) == 1)
    {
        struct task *t = create_task(0);
        is_busy(p);
        enqueue(q, t);
        start_next(p, t);
        printer_status(p);
        is_empty(q);
    }
    tick(p);
    free(q);
    free(t);
}

Why does free(t) Become undefined when my *t is within my while loop?

#

Isn't *t defined in main() ?

spark patrol
#

t is a variable local to the while scope, i.e. it gets destroyed and reborn in every iteration of the while loop

#

Which is why you can't access it anymore after the loop

quasi marsh
#

Ah ok