ppos

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit a47d3a7d0a81f33d791519131faed4f0f2a02e68
parent 1c57464d6d34fee8d1e375ba61a31d403bac887e
Author: Gabriel G. de Brito <me@gboncoffee.dev.br>
Date:   Thu,  6 Aug 2026 12:20:40 -0300

Queue.

Diffstat:
Mlib/queue.c | 63+++++++++++++++++++++++++++++++++++++++------------------------
Atad-vazio/makefile | 35+++++++++++++++++++++++++++++++++++
Atad-vazio/map-test.c | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atad-vazio/map-test.txt | 37+++++++++++++++++++++++++++++++++++++
Atad-vazio/map.c | 9+++++++++
Atad-vazio/map.h | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atad-vazio/queue-test.c | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atad-vazio/queue-test.txt | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atad-vazio/queue.c | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atad-vazio/queue.h | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 907 insertions(+), 24 deletions(-)

diff --git a/lib/queue.c b/lib/queue.c @@ -8,25 +8,26 @@ #include "queue.h" +#include <stdio.h> #include <stdlib.h> typedef struct node_t { - node_t* next; - void* item; + struct node_t* next; + void* item; } node_t; -typedef struct { +struct queue_t { node_t* head; node_t* tail; node_t* it; -} queue_t; +}; -queue_t* queue_create() +struct queue_t* queue_create() { - return (queue_t*) calloc(1, sizeof(*queue)); + return (struct queue_t*) calloc(1, sizeof(struct queue_t)); } -int queue_destroy(queue_t* queue) +int queue_destroy(struct queue_t* queue) { if (queue == NULL) return ERROR; @@ -43,7 +44,7 @@ int queue_destroy(queue_t* queue) return NOERROR; } -int queue_add(queue_t* queue, void* item) +int queue_add(struct queue_t* queue, void* item) { if (queue == NULL) return ERROR; @@ -58,18 +59,23 @@ int queue_add(queue_t* queue, void* item) queue->it = new; } else { queue->tail->next = new; + queue->tail = new; } return NOERROR; } -int queue_del(queue_t* queue, void* item) +int queue_del(struct queue_t* queue, void* item) { + if (queue == NULL) + return ERROR; node_t** prev = &queue->head; node_t* node = queue->head; while (node != NULL) { if (node->item == item) { *prev = node->next; + if (queue->it == node) + queue->it = node->next; free(node); return NOERROR; } @@ -80,7 +86,7 @@ int queue_del(queue_t* queue, void* item) return ERROR; } -bool queue_has(queue_t* queue, void* item) +bool queue_has(struct queue_t* queue, void* item) { for (node_t* node = queue->head; node != NULL; node = node->next) { if (node->item == item) @@ -89,41 +95,47 @@ bool queue_has(queue_t* queue, void* item) return false; } -int queue_size(queue_t* queue) +int queue_size(struct queue_t* queue) { + if (queue == NULL) + return ERROR; + int n = 0; for (node_t* node = queue->head; node != NULL; node = node->next) n += 1; return n; } -void* queue_head(queue_t* queue) +void* queue_head(struct queue_t* queue) { - return queue->head; + if (queue == NULL) + return NULL; + queue->it = queue->head; + if (queue->head == NULL) + return NULL; + return queue->head->item; } -void* queue_next(queue_t* queue) +void* queue_next(struct queue_t* queue) { - if (queue->it == NULL) + if (queue == NULL || queue->it == NULL) return NULL; - void* item = queue->it->item; - queue->it = queue->it->next; if (queue->it == NULL) - queue->it = queue->head; + return NULL; - return item; + return queue->it->item; } -void* queue_item(queue_t* queue) +void* queue_item(struct queue_t* queue) { - if (queue->it == NULL) + if (queue == NULL || queue->it == NULL) return NULL; return queue->it->item; } -void queue_print(char* name, queue_t* queue, void(func)(void*)) +void queue_print(char* name, struct queue_t* queue, void(func)(void*)) { printf("%s: ", name); if (queue == NULL) { @@ -135,9 +147,12 @@ void queue_print(char* name, queue_t* queue, void(func)(void*)) int i = 0; for (node_t* node = queue->head; node != NULL; node = node->next) { i += 1; - func(node->item); + if (func != NULL) + func(node->item); + else + printf("undef"); printf(" "); } - printf("] (%d ite%s)\n", i, i == 1 ? "em" : "ns"); + printf("] (%d items)\n", i); } diff --git a/tad-vazio/makefile b/tad-vazio/makefile @@ -0,0 +1,35 @@ +# TADs filas genéricas e mapa de IDs +# Prof. Carlos A. Maziero, DINF UFPR +# Versão 2.1 - 07/2026 + +# ATENÇÃO: ESTE ARQUIVO NÃO DEVE SER ALTERADO; +# ALTERAÇÕES SERÃO DESCARTADAS NA CORREÇÃO. + +# flags de compilação e ligação +CC = gcc +CFLAGS = -Wall -Wextra -g -std=c99 +BIN = map-test queue-test + +# estes alvos não são arquivos +.PHONY: clean purge + +all: $(BIN) + +# compila fila genérica +queue-test: queue-test.o queue.o +queue-test.o: queue-test.c queue.h +queue.o: queue.c queue.h + +# compila mapa de IDs +map-test: map-test.o map.o +map-test.o: map-test.c map.h +map.o: map.c map.h + +# limpa arquivos temporários +clean: + -rm -f *.o *~ + +# limpa tudo, deixa só o o código-fonte +purge: clean + -rm -f $(BIN) + diff --git a/tad-vazio/map-test.c b/tad-vazio/map-test.c @@ -0,0 +1,149 @@ +// PingPongOS - PingPong Operating System +// Prof. Carlos A. Maziero, DINF UFPR +// Versão 2.1 -- 07/2026 + +// ATENÇÃO: ESTE ARQUIVO NÃO DEVE SER ALTERADO; +// ALTERAÇÕES SERÃO DESCARTADAS NA CORREÇÃO. + +// Teste do TAD mapa de objetos + +#include <stdio.h> +#include <assert.h> +#include "map.h" + +char *fruta[] = {"banana", "uva", "morango", "goiaba", + "laranja", "pera", "melancia", "jaca"}; + +int main() +{ + struct map_t *a; + int id; + char *obj; + + // create + a = map_create(5); + map_print("map", a); + assert(a); + + printf("\n"); + + // put + obj = fruta[0]; + id = map_put(a, obj); + assert(id >= 0); + printf("Object \"%s\" registered under ID %d\n", obj, id); + map_print("map", a); + + // store + obj = fruta[1]; + id = map_put(a, obj); + assert(id >= 0); + printf("Object \"%s\" registered under ID %d\n", obj, id); + map_print("map", a); + + // store + obj = fruta[2]; + id = map_put(a, obj); + assert(id >= 0); + printf("Object \"%s\" registered under ID %d\n", obj, id); + map_print("map", a); + + // store + obj = fruta[3]; + id = map_put(a, obj); + assert(id >= 0); + printf("Object \"%s\" registered under ID %d\n", obj, id); + map_print("map", a); + + // store + obj = fruta[4]; + id = map_put(a, obj); + assert(id >= 0); + printf("Object \"%s\" registered under ID %d\n", obj, id); + map_print("map", a); + + // store (error) + obj = fruta[5]; + id = map_put(a, obj); + assert(id < 0); + printf("Object \"%s\" not registered\n", obj); + map_print("map", a); + + printf("\n"); + + // retrieve + id = 0; + obj = map_get(a, id); + assert(obj == fruta[0]); + printf("Object under ID %d is \"%s\"\n", id, obj); + map_print("map", a); + + // retrieve + id = 4; + obj = map_get(a, id); + assert(obj == fruta[4]); + printf("Object under ID %d is \"%s\"\n", id, obj); + map_print("map", a); + + // retrieve (error) + id = 5; + obj = map_get(a, id); + assert(obj == NULL); + printf("ID %d is not associated to an object\n", id); + map_print("map", a); + + printf("\n"); + + // release + id = 3; + obj = map_del(a, id); + assert(obj == fruta[3]); + printf("ID %d deleted had object \"%s\"\n", id, obj); + map_print("map", a); + + // release + id = 1; + obj = map_del(a, id); + assert(obj == fruta[1]); + printf("ID %d deleted had object \"%s\"\n", id, obj); + map_print("map", a); + + // release (error) + id = 5; + obj = map_del(a, id); + assert(obj == NULL); + printf("ID %d is not associated to an object\n", id); + map_print("map", a); + + printf("\n"); + + // store + obj = fruta[6]; + id = map_put(a, obj); + assert(id == 1); + printf("Object \"%s\" registered under ID %d\n", obj, id); + map_print("map", a); + + // store + obj = fruta[5]; + id = map_put(a, obj); + assert(id == 3); + printf("Object \"%s\" registered under ID %d\n", obj, id); + map_print("map", a); + + // store (error) + obj = fruta[7]; + id = map_put(a, obj); + assert(id == -1); + printf("Object \"%s\" not registered\n", obj); + map_print("map", a); + + printf("\n"); + + map_destroy(a); + printf("Map destroyed\n"); + + printf("Testes concluídos com sucesso!\n"); + return(0); +} + diff --git a/tad-vazio/map-test.txt b/tad-vazio/map-test.txt @@ -0,0 +1,37 @@ +map: [ - - - - - ] (0/5) + +Object "banana" registered under ID 0 +map: [ * - - - - ] (1/5) +Object "uva" registered under ID 1 +map: [ * * - - - ] (2/5) +Object "morango" registered under ID 2 +map: [ * * * - - ] (3/5) +Object "goiaba" registered under ID 3 +map: [ * * * * - ] (4/5) +Object "laranja" registered under ID 4 +map: [ * * * * * ] (5/5) +Object "pera" not registered +map: [ * * * * * ] (5/5) + +Object under ID 0 is "banana" +map: [ * * * * * ] (5/5) +Object under ID 4 is "laranja" +map: [ * * * * * ] (5/5) +ID 5 is not associated to an object +map: [ * * * * * ] (5/5) + +ID 3 deleted had object "goiaba" +map: [ * * * - * ] (4/5) +ID 1 deleted had object "uva" +map: [ * - * - * ] (3/5) +ID 5 is not associated to an object +map: [ * - * - * ] (3/5) + +Object "melancia" registered under ID 1 +map: [ * * * - * ] (4/5) +Object "pera" registered under ID 3 +map: [ * * * * * ] (5/5) +Object "jaca" not registered +map: [ * * * * * ] (5/5) + +Map destroyed diff --git a/tad-vazio/map.c b/tad-vazio/map.c @@ -0,0 +1,9 @@ +// PingPongOS - PingPong Operating System +// Prof. Carlos A. Maziero, DINF UFPR +// Versão 2.1 -- 07/2026 + +// Este arquivo PODE/DEVE ser alterado. + +// Implementação do TAD Mapa de objetos + + diff --git a/tad-vazio/map.h b/tad-vazio/map.h @@ -0,0 +1,69 @@ +// PingPongOS - PingPong Operating System +// Prof. Carlos A. Maziero, DINF UFPR +// Versão 2.1 -- 07/2026 + +// ATENÇÃO: ESTE ARQUIVO NÃO DEVE SER ALTERADO; +// ALTERAÇÕES SERÃO DESCARTADAS NA CORREÇÃO. + +/* +TAD mapa de objetos, que registra objetos de tipo "void *". Um mapa de tamanho +SIZE registra cada objeto sob um identificador único (ID), que varia entre 0 +e SIZE-1 de forma crescente (0, 1, 2, ...). Ao registrar um objeto deve ser +usado o próximo ID livre, com comportamento circular caso não existam mais +IDs livres no final do mapa. +*/ + +#ifndef __MAP__ +#define __MAP__ + +// códigos de retorno das funções +#ifndef ERROR +#define ERROR -1 +#define NOERROR 0 +#endif + +// ponteiro nulo +#ifndef NULL +#define NULL ((void *)0) +#endif + +// Struct opaco que representa um mapa de objetos. +struct map_t; + +// Cria um mapa para até N objetos, com IDs entre 0 e N-1. +// Retorno: ponteiro para o mapa ou NULL (erro) +struct map_t *map_create(int size); + +// destrói um mapa existente (mas não destrói os objetos). +// Retorno: 0 em sucesso ou -1 (erro) +int map_destroy(struct map_t *map); + +// Registra um objeto no mapa, retornando seu ID. +// Retorno: ID atribuído ao objeto ou -1 (erro). +int map_put(struct map_t *map, void *object); + +// Informa o objeto registrado no ID indicado do mapa. +// Retorno: ponteiro para o objeto ou NULL (erro) +void *map_get(struct map_t *map, int id); + +// Libera um ID do mapa e devolve o objeto associado. +// Retorno: ponteiro para o objeto ou NULL (erro) +void *map_del(struct map_t *map, int id); + +// Informa o número de objetos registrados no mapa. +// Retorno: número de objetos registrados ou -1 (erro) +int map_items(struct map_t *map); + +// Informa o número de objetos que o mapa pode registrar. +// Retorno: número de objetos ou -1 (erro) +int map_size(struct map_t *map); + +// Imprime o conteúdo do mapa, no seguinte formato: +// Mapa nulo: nome: undef +// Mapa vazio: nome: [ - - - - - ] (0/5) +// Mapa qualquer: nome: [ - * - * * ] (3/5) +// As posições "*" no vetor impresso correspondem aos IDs em uso no mapa; +// (3/5) indica que o mapa tem 3 objetos e pode registrar até 5 objetos. +void map_print(char *name, struct map_t *map); + +#endif diff --git a/tad-vazio/queue-test.c b/tad-vazio/queue-test.c @@ -0,0 +1,229 @@ +// TAD filas genéricas +// Prof. Carlos A. Maziero, DINF UFPR +// Versão 1.0 - 09/2025 + +// ATENÇÃO: ESTE ARQUIVO NÃO DEVE SER ALTERADO; +// ALTERAÇÕES SERÃO DESCARTADAS NA CORREÇÃO. + +// Teste do TAD fila genérica (fila de itens void *) +// usando uma fila de strings com nomes de frutas. + +#include <stdio.h> +#include <assert.h> +#include "queue.h" + +// verifica o sistema operacional +#ifndef __linux__ +#error "Este código foi planejado para ambientes Linux." +#endif + +// imprime na tela um elemento da fila (chamada pela função queue_print) +void print_item(void *ptr) +{ + printf("%s", (char *)ptr); +} + +int main() +{ + char *fruta[] = {"ameixa", "banana", "goiaba", + "laranja", "morango", "uva"}; + int num_frutas = 6; + struct queue_t *q; + char *item; + int pos, status; + + // Testes com fila inexistente + printf("1 Testes com uma fila inexistente\n"); + q = NULL; + + // tamanho deve ser ERROR + printf(" teste queue_size\n"); + assert(queue_size(q) == ERROR); + + // destruir deve retornar ERROR + printf(" teste queue_destroy\n"); + status = queue_destroy(q); + assert(status == ERROR); + + // operações com iterador devem retornar NULL + printf(" teste queue_head\n"); + assert(queue_head(q) == NULL); + printf(" teste queue_next\n"); + assert(queue_next(q) == NULL); + printf(" teste queue_item\n"); + assert(queue_item(q) == NULL); + + // inserção e remoção devem deve retornar ERROR + printf(" teste queue_add\n"); + assert(queue_add(q, "teste") == ERROR); + printf(" teste queue_del\n"); + assert(queue_del(q, "teste") == ERROR); + + queue_print(" fila", q, print_item); + + // Testes com fila existente, mas vazia + printf("2 Testes com uma fila existente mas vazia\n"); + + // cria a fila + printf(" teste queue_create\n"); + q = queue_create(); + assert(q); + + // tamanho deve ser 0 + printf(" teste queue_size\n"); + assert(queue_size(q) == 0); + + // operações com iterador devem retornar NULL + printf(" teste queue_head\n"); + assert(queue_head(q) == NULL); + printf(" teste queue_next\n"); + assert(queue_next(q) == NULL); + printf(" teste queue_item\n"); + assert(queue_item(q) == NULL); + + // remoção deve deve retornar NULL + printf(" teste queue_del\n"); + assert(queue_del(q, "teste") == ERROR); + + queue_print(" fila", q, print_item); + + // Testes de inserção + printf("3 Testes de inserção\n"); + + for (int i = 0; i < num_frutas; i++) + { + item = fruta[i]; + printf(" colocando %s\n", item); + assert(queue_add(q, item) == NOERROR); + assert(queue_size(q) == (i + 1)); + queue_print(" fila", q, print_item); + } + + printf("4 Testes do queue_print:\n"); + + queue_print(" fila", NULL, print_item); + queue_print(" fila", q, NULL); + + printf("5 Testes do iterador:\n"); + + // iterador deve apontar para a primeira posição + item = queue_item(q); + pos = 0; + + // testa se iterador aponta e se desloca corretamente + while (item) + { + printf(" iterador em %s (posição %d)\n", item, pos); + assert(item == fruta[pos]); + item = queue_next(q); + pos++; + } + printf(" iterador em %s\n", (char *)queue_item(q)); + + // testando queue_head + assert(queue_head(q) == fruta[0]); + assert(queue_item(q) == fruta[0]); + + printf("6 Testes de remoção\n"); + + // testando queue_del com fila NULL + printf(" retirando de fila NULL\n"); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_del(NULL, fruta[0]) == ERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[0]); + + // testando queue_del com item NULL + printf(" retirando item NULL\n"); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_del(q, NULL) == ERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[0]); + + // testando queue_del com item que não está na fila + printf(" retirando acerola (que não está na fila)\n"); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_del(q, "acerola") == ERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[0]); + + // testando queue_del com item no meio da fila + pos = num_frutas / 2; + printf(" retirando %s (no meio da fila)\n", fruta[pos]); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_del(q, fruta[pos]) == NOERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[0]); + + // testando queue_del com item no inicio da fila + pos = 0; + printf(" retirando %s (no início da fila)\n", fruta[pos]); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_del(q, fruta[pos]) == NOERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[1]); + + // testando queue_del com item no fim da fila + pos = num_frutas - 1; + printf(" retirando %s (no fim da fila)\n", fruta[pos]); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_del(q, fruta[pos]) == NOERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[1]); + + // testando queue_del com item apontado pelo iterador, no meio + queue_next(q); + pos = 2; + printf(" retirando sob o iterador\n"); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[pos]); + assert(queue_del(q, fruta[pos]) == NOERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[4]); + + // testando queue_del com item apontado pelo iterador, no fim + pos = 4; + printf(" retirando sob o iterador\n"); + queue_print(" fila antes ", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == fruta[pos]); + assert(queue_del(q, fruta[pos]) == NOERROR); + queue_print(" fila depois", q, print_item); + printf(" iterador em %s\n", (char *)queue_item(q)); + assert(queue_item(q) == NULL); + + // esvaziando a fila + printf("7 Esvaziando a fila\n"); + queue_print(" fila", q, print_item); + item = queue_head(q); + while (item) + { + assert(queue_del(q, item) == NOERROR); + printf(" retirei %s\n", item); + queue_print(" fila", q, print_item); + item = queue_item(q); + } + assert(queue_size(q) == 0); + + // testando queue_destroy + printf("8 Teste queue_destroy\n"); + status = queue_destroy(q); + assert(status == NOERROR); + + printf("Testes concluídos com sucesso!\n"); + return(0); +} diff --git a/tad-vazio/queue-test.txt b/tad-vazio/queue-test.txt @@ -0,0 +1,88 @@ +1 Testes com uma fila inexistente + teste queue_size + teste queue_destroy + teste queue_head + teste queue_next + teste queue_item + teste queue_add + teste queue_del + fila: undef +2 Testes com uma fila existente mas vazia + teste queue_create + teste queue_size + teste queue_head + teste queue_next + teste queue_item + teste queue_del + fila: [ ] (0 items) +3 Testes de inserção + colocando ameixa + fila: [ ameixa ] (1 items) + colocando banana + fila: [ ameixa banana ] (2 items) + colocando goiaba + fila: [ ameixa banana goiaba ] (3 items) + colocando laranja + fila: [ ameixa banana goiaba laranja ] (4 items) + colocando morango + fila: [ ameixa banana goiaba laranja morango ] (5 items) + colocando uva + fila: [ ameixa banana goiaba laranja morango uva ] (6 items) +4 Testes do queue_print: + fila: undef + fila: [ undef undef undef undef undef undef ] (6 items) +5 Testes do iterador: + iterador em ameixa (posição 0) + iterador em banana (posição 1) + iterador em goiaba (posição 2) + iterador em laranja (posição 3) + iterador em morango (posição 4) + iterador em uva (posição 5) + iterador em (null) +6 Testes de remoção + retirando de fila NULL + fila antes : [ ameixa banana goiaba laranja morango uva ] (6 items) + iterador em ameixa + fila depois: [ ameixa banana goiaba laranja morango uva ] (6 items) + iterador em ameixa + retirando item NULL + fila antes : [ ameixa banana goiaba laranja morango uva ] (6 items) + iterador em ameixa + fila depois: [ ameixa banana goiaba laranja morango uva ] (6 items) + iterador em ameixa + retirando acerola (que não está na fila) + fila antes : [ ameixa banana goiaba laranja morango uva ] (6 items) + iterador em ameixa + fila depois: [ ameixa banana goiaba laranja morango uva ] (6 items) + iterador em ameixa + retirando laranja (no meio da fila) + fila antes : [ ameixa banana goiaba laranja morango uva ] (6 items) + iterador em ameixa + fila depois: [ ameixa banana goiaba morango uva ] (5 items) + iterador em ameixa + retirando ameixa (no início da fila) + fila antes : [ ameixa banana goiaba morango uva ] (5 items) + iterador em ameixa + fila depois: [ banana goiaba morango uva ] (4 items) + iterador em banana + retirando uva (no fim da fila) + fila antes : [ banana goiaba morango uva ] (4 items) + iterador em banana + fila depois: [ banana goiaba morango ] (3 items) + iterador em banana + retirando sob o iterador + fila antes : [ banana goiaba morango ] (3 items) + iterador em goiaba + fila depois: [ banana morango ] (2 items) + iterador em morango + retirando sob o iterador + fila antes : [ banana morango ] (2 items) + iterador em morango + fila depois: [ banana ] (1 items) + iterador em (null) +7 Esvaziando a fila + fila: [ banana ] (1 items) + retirei banana + fila: [ ] (0 items) +8 Teste queue_destroy +Testes concluídos com sucesso! diff --git a/tad-vazio/queue.c b/tad-vazio/queue.c @@ -0,0 +1,158 @@ +// PingPongOS - PingPong Operating System +// © Prof. Carlos A. Maziero, DINF UFPR +// Versão 2.1 -- 06/2026 + +// Este arquivo PODE/DEVE ser alterado. + +// Implementação do TAD fila genérica + +#include "queue.h" + +#include <stdio.h> +#include <stdlib.h> + +typedef struct node_t { + struct node_t* next; + void* item; +} node_t; + +struct queue_t { + node_t* head; + node_t* tail; + node_t* it; +}; + +struct queue_t* queue_create() +{ + return (struct queue_t*) calloc(1, sizeof(struct queue_t)); +} + +int queue_destroy(struct queue_t* queue) +{ + if (queue == NULL) + return ERROR; + + node_t* node = queue->head; + while (node != NULL) { + node_t* n = node; + node = node->next; + free(n); + } + + free(queue); + + return NOERROR; +} + +int queue_add(struct queue_t* queue, void* item) +{ + if (queue == NULL) + return ERROR; + + node_t* new = malloc(sizeof(*new)); + new->item = item; + new->next = NULL; + + if (queue->tail == NULL) { + queue->tail = new; + queue->head = new; + queue->it = new; + } else { + queue->tail->next = new; + queue->tail = new; + } + + return NOERROR; +} + +int queue_del(struct queue_t* queue, void* item) +{ + if (queue == NULL) + return ERROR; + node_t** prev = &queue->head; + node_t* node = queue->head; + while (node != NULL) { + if (node->item == item) { + *prev = node->next; + if (queue->it == node) + queue->it = node->next; + free(node); + return NOERROR; + } + prev = &node->next; + node = node->next; + } + + return ERROR; +} + +bool queue_has(struct queue_t* queue, void* item) +{ + for (node_t* node = queue->head; node != NULL; node = node->next) { + if (node->item == item) + return true; + } + return false; +} + +int queue_size(struct queue_t* queue) +{ + if (queue == NULL) + return ERROR; + + int n = 0; + for (node_t* node = queue->head; node != NULL; node = node->next) + n += 1; + return n; +} + +void* queue_head(struct queue_t* queue) +{ + if (queue == NULL) + return NULL; + queue->it = queue->head; + if (queue->head == NULL) + return NULL; + return queue->head->item; +} + +void* queue_next(struct queue_t* queue) +{ + if (queue == NULL || queue->it == NULL) + return NULL; + + queue->it = queue->it->next; + if (queue->it == NULL) + return NULL; + + return queue->it->item; +} + +void* queue_item(struct queue_t* queue) +{ + if (queue == NULL || queue->it == NULL) + return NULL; + return queue->it->item; +} + +void queue_print(char* name, struct queue_t* queue, void(func)(void*)) +{ + printf("%s: ", name); + if (queue == NULL) { + printf("undef\n"); + return; + } + printf("[ "); + + int i = 0; + for (node_t* node = queue->head; node != NULL; node = node->next) { + i += 1; + if (func != NULL) + func(node->item); + else + printf("undef"); + printf(" "); + } + + printf("] (%d items)\n", i); +} diff --git a/tad-vazio/queue.h b/tad-vazio/queue.h @@ -0,0 +1,94 @@ +// PingPongOS - PingPong Operating System +// Prof. Carlos A. Maziero, DINF UFPR +// Versão 2.0 -- 06/2025 + +// ATENÇÃO: ESTE ARQUIVO NÃO DEVE SER ALTERADO; +// ALTERAÇÕES SERÃO DESCARTADAS NA CORREÇÃO. + +/* +TAD fila genérica de ponteiros, que armazena itens de tipo "void *". +A fila mantém um iterador que aponta para um item da fila (ou para NULL). +O iterador pode ser ajustado usando as funções queue_head() e queue_next() +e ter seu item consultado com a função queue_item(). Inicialmente o iterador +aponta para o começo da fila. +*/ + +#ifndef __QUEUE__ +#define __QUEUE__ + +#include <stdbool.h> + +// códigos de retorno das funções +#ifndef ERROR +#define ERROR -1 +#define NOERROR 0 +#endif + +// ponteiro nulo +#ifndef NULL +#define NULL ((void *)0) +#endif + +// struct que representa uma fila; este é um struct "opaco", +// que deve ser redefinido completamente em queue.c +struct queue_t; + +// Cria uma fila inicialmente vazia. +// Retorno: ponteiro p/ a nova fila +// NULL se houver erro +struct queue_t *queue_create(); + +// Destroi uma fila, liberando a memória alocada por ela. +// IMPORTANTE: os itens apontados pela fila NÃO devem ser liberados, +// pois a aplicação que os criou e pôs na fila é responsável por eles. +// Retorno: NOERROR ou ERROR (se a fila não existir) +int queue_destroy(struct queue_t *queue); + +// Adiciona um item no fim da fila; ajusta o iterador para ele +// se for o primeiro item (ou seja, se a fila estiver vazia). +// Retorno: NOERROR ou ERROR (se fila ou item não existir) +int queue_add(struct queue_t *queue, void *item); + +// Retira da fila o item com o valor indicado; se o item estiver +// em mais de uma posição da fila, retira apenas da primeira posição +// encontrada; se o item estiver apontado pelo iterador, este avança +// para o próximo item da fila (ou para NULL, se for o último). +// Retorno: NOERROR ou ERROR (não encontrou ou outro erro). +int queue_del(struct queue_t *queue, void *item); + +// Informa se o item indicado está na fila. +// Retorno: true/false (error: false). +bool queue_has(struct queue_t *queue, void *item); + +// Informa o número de itens na fila. +// Retorno: número de itens na fila (>= 0) +// ERROR se a fila não existir +int queue_size(struct queue_t *queue); + +// Põe o iterador no início da fila. +// Retorno: ptr para o item apontado pelo iterador +// NULL se a fila estiver vazia ou não existir +void *queue_head(struct queue_t *queue); + +// Avança o iterador ao próximo item na fila. +// Retorno: ptr para o item apontado pelo iterador após avançar +// NULL se o iterador passou do último item da fila +// NULL se a fila estiver vazia ou não existir +void *queue_next(struct queue_t *queue); + +// Informa o item atualmente sob o iterador na fila. +// Retorno: ptr para o item apontado pelo iterador +// NULL se a fila estiver vazia ou não existir +// NULL se o iterador passou do fim da fila +void *queue_item(struct queue_t *queue); + +// Imprime os elementos de uma fila; a função externa "func" +// deve ser chamada para imprimir cada item. +// Exemplos de saída, com name == "Frutas": +// Frutas: [ banana pera ameixa uva ] (4 items) +// Frutas: [ ] (0 items) +// Frutas: undef se queue == NULL +// Frutas: [ undef undef undef ] (3 items) se func == NULL +void queue_print(char *name, struct queue_t *queue, void(func)(void *)); + +#endif