Added merge function variety with watchdog
|
@ -0,0 +1,12 @@
|
|||
*
|
||||
!*/
|
||||
!.gitignore
|
||||
!.README.md
|
||||
!LICENSE
|
||||
!/Algoritmos*/*/*.c
|
||||
!/Cálculo*/Semana*/*.pdf
|
||||
!/Introdução*/Lista*/*.pdf
|
||||
!/Introdução*/EP*/*.pdf
|
||||
!/Matemática*/Lista*/*.pdf
|
||||
!/Matrizes*/Listas/*.pdf
|
||||
!/Matrizes*/Resumos/*.pdf
|
|
@ -0,0 +1,192 @@
|
|||
/*********************************************************************/
|
||||
/** ACH2023 - Algoritmos e Estruturas de Dados I **/
|
||||
/** EACH-USP - Segundo Semestre de 2021 **/
|
||||
/** Turma 04 - Prof. Luciano Antonio Digiampietri **/
|
||||
/** **/
|
||||
/** EP 1 - Lista Ligada de Produtos **/
|
||||
/** **/
|
||||
/** Guilherme de Abreu Barreto nUSP: 12543033 **/
|
||||
/** **/
|
||||
/*********************************************************************/
|
||||
#include "listadeprodutos.h"
|
||||
|
||||
PLISTA criarLista(){
|
||||
PLISTA res = (PLISTA) malloc(sizeof(LISTADEPRODUTOS));
|
||||
int x;
|
||||
for (x=0;x<NUMTIPOS;x++){
|
||||
res->LISTADELISTAS[x]=(PONT) malloc(sizeof(REGISTRO));
|
||||
res->LISTADELISTAS[x]->id=-1;
|
||||
res->LISTADELISTAS[x]->quantidade=0;
|
||||
res->LISTADELISTAS[x]->valorUnitario=0;
|
||||
res->LISTADELISTAS[x]->proxProd=NULL;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
int tamanho(PLISTA l){
|
||||
int tam = 0;
|
||||
int x;
|
||||
PONT atual;
|
||||
for (x=0;x<NUMTIPOS;x++){
|
||||
atual = l->LISTADELISTAS[x]->proxProd;
|
||||
while (atual) {
|
||||
atual = atual->proxProd;
|
||||
tam++;
|
||||
}
|
||||
}
|
||||
return tam;
|
||||
}
|
||||
|
||||
PONT buscarID(PLISTA l, int id){
|
||||
int x;
|
||||
PONT atual;
|
||||
for (x=0;x<NUMTIPOS;x++){
|
||||
atual = l->LISTADELISTAS[x]->proxProd;
|
||||
while (atual) {
|
||||
if (atual->id == id) return atual;
|
||||
atual = atual->proxProd;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
PONT buscarIDTipo(PLISTA l, int id, int tipo){
|
||||
if (tipo<0 || tipo>=NUMTIPOS) return NULL;
|
||||
PONT atual = l->LISTADELISTAS[tipo]->proxProd;
|
||||
while (atual) {
|
||||
if (atual->id == id) return atual;
|
||||
atual = atual->proxProd;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void exibirLog(PLISTA f){
|
||||
int numElementos = tamanho(f);
|
||||
printf("Log lista [elementos: %i]\n", numElementos);
|
||||
int x;
|
||||
PONT atual;
|
||||
for (x=0;x<NUMTIPOS;x++){
|
||||
printf(" #TIPO: %i -> ", x);
|
||||
atual = f->LISTADELISTAS[x]->proxProd;
|
||||
while (atual){
|
||||
printf(" [%i;%i;%i;$%i]", atual->id, atual->quantidade, atual->valorUnitario, atual->quantidade*atual->valorUnitario);
|
||||
atual = atual->proxProd;
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int consultarValorUnitario(PLISTA l, int id){
|
||||
int x;
|
||||
PONT atual;
|
||||
for (x=0;x<NUMTIPOS;x++){
|
||||
atual = l->LISTADELISTAS[x]->proxProd;
|
||||
while (atual) {
|
||||
if (atual->id == id) return atual->valorUnitario;
|
||||
atual = atual->proxProd;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Anotações quanto a inserção:
|
||||
|
||||
- Uma lista ligada para cada tipo de produto
|
||||
|
||||
- PLISTA: Variável que armazena um ponteiro para a lista [array] de listas [ligadas].
|
||||
|
||||
- A função necessita proibir a inserção de um novo produto de mesmo identificador que um produto já presente em *qualquer uma* das listas listadas
|
||||
|
||||
- 0 ≤ id ≤ NUMTIPOS -1
|
||||
|
||||
- quantidade, valor ≥ 0
|
||||
|
||||
- Se o valor total for igual, inserir antes.
|
||||
*/
|
||||
|
||||
/* Funções auxiliares */
|
||||
|
||||
bool buscarTudoSobre (PLISTA l, int id, int *tipo, PONT *atual, PONT *ant) {
|
||||
for (*tipo = 0; *tipo < NUMTIPOS; *tipo = *tipo + 1){
|
||||
*ant = l->LISTADELISTAS[*tipo];
|
||||
*atual = (*ant)->proxProd;
|
||||
while (*atual && (*atual)->id != id) {
|
||||
*ant = *atual;
|
||||
*atual = (*atual)->proxProd;
|
||||
}
|
||||
if (*atual)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void apagarRegistro(PONT atual, PONT ant) {
|
||||
ant->proxProd = atual->proxProd;
|
||||
free(atual);
|
||||
}
|
||||
|
||||
/* Funções principais */
|
||||
|
||||
bool inserirNovoProduto(PLISTA l, int id, int tipo, int quantidade, int valor){
|
||||
PONT p, novo;
|
||||
|
||||
if (id < 1
|
||||
|| tipo < 0
|
||||
|| tipo >= NUMTIPOS
|
||||
|| quantidade < 1
|
||||
|| valor < 1
|
||||
|| buscarID(l, id))
|
||||
return false;
|
||||
|
||||
novo = malloc(sizeof(REGISTRO));
|
||||
novo->id = id;
|
||||
novo->quantidade = quantidade;
|
||||
novo->valorUnitario = valor;
|
||||
p = l->LISTADELISTAS[tipo];
|
||||
|
||||
while (p->proxProd
|
||||
&& p->proxProd->valorUnitario * p->proxProd->quantidade < valor * quantidade)
|
||||
p = p->proxProd;
|
||||
|
||||
novo->proxProd = p->proxProd;
|
||||
p->proxProd = novo;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool removerItensDeUmProduto(PLISTA l, int id, int quantidade){
|
||||
int tipo, valor;
|
||||
PONT atual, ant;
|
||||
|
||||
if (quantidade <= 0
|
||||
|| !buscarTudoSobre(l, id, &tipo, &atual, &ant)
|
||||
|| quantidade > atual->quantidade)
|
||||
return false;
|
||||
|
||||
atual->quantidade -= quantidade;
|
||||
quantidade = atual->quantidade;
|
||||
valor = atual->valorUnitario;
|
||||
|
||||
if (quantidade * valor > ant->quantidade * ant-> valorUnitario)
|
||||
return true;
|
||||
|
||||
apagarRegistro(atual, ant);
|
||||
|
||||
if (quantidade == 0)
|
||||
return true;
|
||||
return inserirNovoProduto(l, id, tipo, quantidade, valor);
|
||||
}
|
||||
|
||||
bool atualizarValorDoProduto(PLISTA l, int id, int valor){
|
||||
int tipo, quantidade;
|
||||
PONT atual, ant;
|
||||
|
||||
if (valor <= 0 || !buscarTudoSobre(l, id, &tipo, &atual, &ant))
|
||||
return false;
|
||||
|
||||
quantidade = atual->quantidade;
|
||||
apagarRegistro(atual, ant);
|
||||
|
||||
return inserirNovoProduto(l, id, tipo, quantidade, valor);
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#define NUMTIPOS 10
|
||||
#define true 1
|
||||
#define false 0
|
||||
|
||||
typedef int bool;
|
||||
|
||||
typedef struct aux {
|
||||
int id;
|
||||
int quantidade;
|
||||
int valorUnitario;
|
||||
struct aux* proxProd;
|
||||
} REGISTRO, * PONT;
|
||||
|
||||
|
||||
typedef struct {
|
||||
PONT LISTADELISTAS[NUMTIPOS];
|
||||
} LISTADEPRODUTOS, * PLISTA;
|
||||
|
||||
|
||||
|
||||
PLISTA criarLista();
|
||||
|
||||
int tamanho(PLISTA l);
|
||||
|
||||
int consultarValorUnitario(PLISTA l, int id);
|
||||
|
||||
PONT buscarID(PLISTA l, int id);
|
||||
|
||||
PONT buscarIDTipo(PLISTA l, int id, int tipo);
|
||||
|
||||
|
||||
|
||||
|
||||
bool inserirNovoProduto(PLISTA l, int id, int tipo, int quantidade, int valor);
|
||||
|
||||
bool atualizarValorDoProduto(PLISTA l, int id, int valor);
|
||||
|
||||
bool removerItensDeUmProduto(PLISTA l, int id, int quantidade);
|
|
@ -0,0 +1,145 @@
|
|||
#include "listadeprodutos.c"
|
||||
|
||||
int main() {
|
||||
PLISTA f = criarLista();
|
||||
int id;
|
||||
int tipo;
|
||||
int quantidade;
|
||||
int valor;
|
||||
bool res;
|
||||
|
||||
printf("################# INSERINDO #######################\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirNovoProduto(f, 2, 1, 22, 23);
|
||||
if(res) printf("Insercao retornou true (1)\n");
|
||||
else printf("Insercao retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
res = inserirNovoProduto(f, 4, 4, 4, 4);
|
||||
if(res) printf("Insercao retornou true (2)\n");
|
||||
else printf("Insercao retornou false (2)\n");
|
||||
exibirLog(f);
|
||||
res = inserirNovoProduto(f, 6, 1, 8, 9);
|
||||
if(res) printf("Insercao retornou true (3)\n");
|
||||
else printf("Insercao retornou false (3)\n");
|
||||
exibirLog(f);
|
||||
res = inserirNovoProduto(f, 3, 1, 22, 23);
|
||||
if(res) printf("Insercao retornou true (4)\n");
|
||||
else printf("Insercao retornou false (4)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, -5, 6, 7, 8);
|
||||
if(res) printf("Insercao retornou true (5)\n");
|
||||
else printf("Insercao retornou false (5)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, 5, -6, 7, 8);
|
||||
if(res) printf("Insercao retornou true (6)\n");
|
||||
else printf("Insercao retornou false (6)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, 5, 6, -7, 8);
|
||||
if(res) printf("Insercao retornou true (7)\n");
|
||||
else printf("Insercao retornou false (7)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, 5, 6, 7, -8);
|
||||
if(res) printf("Insercao retornou true (8)\n");
|
||||
else printf("Insercao retornou false (8)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, 3, 1, 9, 9);
|
||||
if(res) printf("Insercao retornou true (9)\n");
|
||||
else printf("Insercao retornou false (9)\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
printf("################# REMOVENDO #######################\n");
|
||||
res = removerItensDeUmProduto(f, 4, 1);
|
||||
if(res) printf("Remocao retornou true (1)\n");
|
||||
else printf("Remocao retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = removerItensDeUmProduto(f, 2, 1);
|
||||
if(res) printf("Remocao retornou true (2)\n");
|
||||
else printf("Remocao retornou false (2)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = removerItensDeUmProduto(f, 3, 22);
|
||||
if(res) printf("Remocao retornou true (3)\n");
|
||||
else printf("Remocao retornou false (3)\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
res = removerItensDeUmProduto(f, 20, 1);
|
||||
if(res) printf("Remocao retornou true (4)\n");
|
||||
else printf("Remocao retornou false (4)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = removerItensDeUmProduto(f, 5, 10);
|
||||
if(res) printf("Remocao retornou true (5)\n");
|
||||
else printf("Remocao retornou false (5)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = removerItensDeUmProduto(f, 4, 0);
|
||||
if(res) printf("Remocao retornou true (6)\n");
|
||||
else printf("Remocao retornou false (6)\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
|
||||
printf("################# ATUALIZANDO VALOR #######\n");
|
||||
|
||||
res = atualizarValorDoProduto(f, 6, 1);
|
||||
if(res) printf("Atualizacao retornou true (1)\n");
|
||||
else printf("Atualizacao retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = atualizarValorDoProduto(f, 6, 600);
|
||||
if(res) printf("Atualizacao retornou true (2)\n");
|
||||
else printf("Atualizacao retornou false (2)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = atualizarValorDoProduto(f, 6, 20);
|
||||
if(res) printf("Atualizacao retornou true (3)\n");
|
||||
else printf("Atualizacao retornou false (3)\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
res = atualizarValorDoProduto(f, 6, 0);
|
||||
if(res) printf("Atualizacao retornou true (4)\n");
|
||||
else printf("Atualizacao retornou false (4)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = atualizarValorDoProduto(f, 6, -100);
|
||||
if(res) printf("Atualizacao retornou true (5)\n");
|
||||
else printf("Atualizacao retornou false (5)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = atualizarValorDoProduto(f, 61, 600);
|
||||
if(res) printf("Atualizacao retornou true (6)\n");
|
||||
else printf("Atualizacao retornou false (6)\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
|
||||
res = atualizarValorDoProduto(f, 6, 3);
|
||||
if(res) printf("Atualizacao retornou true (7)\n");
|
||||
else printf("Atualizacao retornou false (7)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = atualizarValorDoProduto(f, 4, 200);
|
||||
if(res) printf("Atualizacao retornou true (8)\n");
|
||||
else printf("Atualizacao retornou false (8)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = atualizarValorDoProduto(f, 2, 20);
|
||||
if(res) printf("Atualizacao retornou true (9)\n");
|
||||
else printf("Atualizacao retornou false (9)\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
#include "listadeprodutos.c"
|
||||
|
||||
int main() {
|
||||
PLISTA f = criarLista();
|
||||
bool res;
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirNovoProduto(f, 3, 3, 3, 3);
|
||||
if(res) printf("Insercao retornou true (1)\n");
|
||||
else printf("Insercao retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, 1, 2, 3, 5);
|
||||
if(res) printf("Insercao retornou true (1)\n");
|
||||
else printf("Insercao retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, 5, 2, 7, 8);
|
||||
if(res) printf("Insercao retornou true (1)\n");
|
||||
else printf("Insercao retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = inserirNovoProduto(f, 9, 2, 11, 12);
|
||||
if(res) printf("Insercao retornou true (1)\n");
|
||||
else printf("Insercao retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = removerItensDeUmProduto(f, 1, 3);
|
||||
if(res) printf("Remoção retornou true (1)\n");
|
||||
else printf("Remoção retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
res = removerItensDeUmProduto(f, 9, 11);
|
||||
if(res) printf("Remoção retornou true (1)\n");
|
||||
else printf("Remoção retornou false (1)\n");
|
||||
exibirLog(f);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
/*********************************************************************/
|
||||
/** ACH2023 - Algoritmos e Estruturas de Dados I **/
|
||||
/** EACH-USP - Segundo Semestre de 2021 **/
|
||||
/** 04 - Prof. Luciano Antonio Digiampietri **/
|
||||
/** **/
|
||||
/** EP 2 - Fila Preferencial **/
|
||||
/** **/
|
||||
/** Guilherme de Abreu Barreto nUSP: 12543033 **/
|
||||
/** **/
|
||||
/*********************************************************************/
|
||||
|
||||
#include "filapreferencial.h"
|
||||
|
||||
PFILA criarFila(){
|
||||
PFILA res = (PFILA) malloc(sizeof(FILAPREFERENCIAL));
|
||||
res->cabeca = (PONT) malloc(sizeof(ELEMENTO));
|
||||
res->inicioNaoPref = res->cabeca;
|
||||
res->cabeca->id = -1;
|
||||
res->cabeca->ehPreferencial = false;
|
||||
res->cabeca->ant = res->cabeca;
|
||||
res->cabeca->prox = res->cabeca;
|
||||
return res;
|
||||
}
|
||||
|
||||
int tamanho(PFILA f){
|
||||
PONT atual = f->cabeca->prox;
|
||||
int tam = 0;
|
||||
while (atual != f->cabeca) {
|
||||
atual = atual->prox;
|
||||
tam++;
|
||||
}
|
||||
return tam;
|
||||
}
|
||||
|
||||
PONT buscarID(PFILA f, int id){
|
||||
PONT atual = f->cabeca->prox;
|
||||
while (atual != f->cabeca) {
|
||||
if (atual->id == id) return atual;
|
||||
atual = atual->prox;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void exibirLog(PFILA f){
|
||||
int numElementos = tamanho(f);
|
||||
printf("\nLog fila [elementos: %i]\t- Inicio:", numElementos);
|
||||
PONT atual = f->cabeca->prox;
|
||||
while (atual != f->cabeca) {
|
||||
printf(" [%i;%i]", atual->id, atual->ehPreferencial);
|
||||
atual = atual->prox;
|
||||
}
|
||||
printf("\n \t- Fim:");
|
||||
atual = f->cabeca->ant;
|
||||
while (atual != f->cabeca) {
|
||||
printf(" [%i;%i]", atual->id, atual->ehPreferencial);
|
||||
atual = atual->ant;
|
||||
}
|
||||
printf("\n\n");
|
||||
}
|
||||
|
||||
|
||||
bool consultarPreferencial(PFILA f, int id){
|
||||
PONT atual = f->cabeca->prox;
|
||||
while (atual != f->cabeca) {
|
||||
if (atual->id == id) return atual->ehPreferencial;
|
||||
atual = atual->prox;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Função auxiliar */
|
||||
void removerDaFila(PFILA f, PONT pessoa) {
|
||||
if(f->inicioNaoPref == pessoa)
|
||||
f->inicioNaoPref = pessoa->prox;
|
||||
pessoa->ant->prox = pessoa->prox;
|
||||
pessoa->prox->ant = pessoa->ant;
|
||||
free(pessoa);
|
||||
}
|
||||
|
||||
bool inserirPessoaNaFila(PFILA f, int id, bool ehPreferencial){
|
||||
PONT pessoa;
|
||||
|
||||
if (!f || id < 0 || buscarID(f,id))
|
||||
return false;
|
||||
pessoa = malloc(sizeof(ELEMENTO));
|
||||
pessoa->id = id;
|
||||
pessoa->ehPreferencial = ehPreferencial;
|
||||
if (ehPreferencial)
|
||||
pessoa->prox = f->inicioNaoPref;
|
||||
else {
|
||||
pessoa->prox = f->cabeca;
|
||||
if (f->inicioNaoPref == f->cabeca)
|
||||
f->inicioNaoPref = pessoa;
|
||||
}
|
||||
pessoa->ant = pessoa->prox->ant;
|
||||
pessoa->prox->ant = pessoa->ant->prox = pessoa;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool atenderPrimeiraDaFila(PFILA f, int* id){
|
||||
if (!f || f->cabeca->prox == f->cabeca)
|
||||
return false;
|
||||
*id = f->cabeca->prox->id;
|
||||
removerDaFila(f, f->cabeca->prox);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool desistirDaFila(PFILA f, int id){
|
||||
PONT pessoa;
|
||||
|
||||
if (!f || id < 0)
|
||||
return false;
|
||||
pessoa = buscarID(f, id);
|
||||
if (!pessoa)
|
||||
return false;
|
||||
removerDaFila(f, pessoa);
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#define true 1
|
||||
#define false 0
|
||||
|
||||
typedef int bool;
|
||||
|
||||
typedef struct aux {
|
||||
int id;
|
||||
bool ehPreferencial;
|
||||
struct aux* ant;
|
||||
struct aux* prox;
|
||||
} ELEMENTO, * PONT;
|
||||
|
||||
typedef struct {
|
||||
PONT cabeca;
|
||||
PONT inicioNaoPref;
|
||||
} FILAPREFERENCIAL, * PFILA;
|
|
@ -0,0 +1,127 @@
|
|||
#include "filapreferencial.c"
|
||||
|
||||
int main() {
|
||||
PFILA f = criarFila();
|
||||
int id;
|
||||
bool ehPreferencial;
|
||||
bool res;
|
||||
|
||||
printf("################# INSERINDO #######################\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, -1, false);
|
||||
if(res) printf("Insercao retornou true (0).\n");
|
||||
else printf("Insercao retornou false (0). [OK]\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 1, false);
|
||||
if(res) printf("Insercao retornou true (1). [OK]\n");
|
||||
else printf("Insercao retornou false (1).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 2, false);
|
||||
if(res) printf("Insercao retornou true (2). [OK]\n");
|
||||
else printf("Insercao retornou false (2).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 3, false);
|
||||
if(res) printf("Insercao retornou true (3). [OK]\n");
|
||||
else printf("Insercao retornou false (3).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 4, true);
|
||||
if(res) printf("Insercao retornou true (4). [OK]\n");
|
||||
else printf("Insercao retornou false (4).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 5, true);
|
||||
if(res) printf("Insercao retornou true (5). [OK]\n");
|
||||
else printf("Insercao retornou false (5).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 6, true);
|
||||
if(res) printf("Insercao retornou true (6). [OK]\n");
|
||||
else printf("Insercao retornou false (6).\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
printf("################# ATENDENDO #######################\n");
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (7), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (7).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (8), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (8).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (9), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (9).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (10), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (10).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (11), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (11).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (12), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (12).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (13), id=%i.\n",id);
|
||||
else printf("Atendimento retornou false (13). [OK]\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
|
||||
printf("################# INSERINDO PARTE 2 ###############\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 7, true);
|
||||
if(res) printf("Insercao retornou true (14). [OK]\n");
|
||||
else printf("Insercao retornou false (14).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 8, false);
|
||||
if(res) printf("Insercao retornou true (15). [OK]\n");
|
||||
else printf("Insercao retornou false (15).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 9, true);
|
||||
if(res) printf("Insercao retornou true (16). [OK]\n");
|
||||
else printf("Insercao retornou false (16).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 10, false);
|
||||
if(res) printf("Insercao retornou true (17). [OK]\n");
|
||||
else printf("Insercao retornou false (17).\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
printf("################# SAINDO DA FILA ##################\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 6);
|
||||
if(res) printf("Desistindo da fila retornou true (18).\n");
|
||||
else printf("Desistindo da fila retornou false (18). [OK]\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 7);
|
||||
if(res) printf("Desistindo da fila retornou true (19). [OK]\n");
|
||||
else printf("Desistindo da fila retornou false (19).\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 8);
|
||||
if(res) printf("Desistindo da fila retornou true (20). [OK]\n");
|
||||
else printf("Desistindo da fila retornou false (20).\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 9);
|
||||
if(res) printf("Desistindo da fila retornou true (21). [OK]\n");
|
||||
else printf("Desistindo da fila retornou false (21).\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 10);
|
||||
if(res) printf("Desistindo da fila retornou true (22). [OK]\n");
|
||||
else printf("Desistindo da fila retornou false (22).\n");
|
||||
exibirLog(f);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,172 @@
|
|||
#include "filapreferencial.c"
|
||||
|
||||
int main() {
|
||||
PFILA f = criarFila();
|
||||
int id;
|
||||
bool ehPreferencial;
|
||||
bool res;
|
||||
|
||||
printf("################# INSERINDO ####################### --- 1\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, -1, false);
|
||||
if(res) printf("Insercao retornou true (0).\n");
|
||||
else printf("Insercao retornou false (0). [OK]\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 1, false);
|
||||
if(res) printf("Insercao retornou true (1). [OK]\n");
|
||||
else printf("Insercao retornou false (1).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 2, false);
|
||||
if(res) printf("Insercao retornou true (2). [OK]\n");
|
||||
else printf("Insercao retornou false (2).\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("################# ATENDENDO ####################### --- 1\n");
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (1), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (1).\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("################# INSERINDO ####################### ---- 2\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 3, false);
|
||||
if(res) printf("Insercao retornou true (3). [OK]\n");
|
||||
else printf("Insercao retornou false (3).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 4, true);
|
||||
if(res) printf("Insercao retornou true (4). [OK]\n");
|
||||
else printf("Insercao retornou false (4).\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("################# SAINDO DA FILA ################## ---- 1\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 3);
|
||||
if(res) printf("Desistindo da fila retornou true (1).\n");
|
||||
else printf("Desistindo da fila retornou false (1). [OK]\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("################# INSERINDO ####################### ---- 3\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 5, true);
|
||||
if(res) printf("Insercao retornou true (5). [OK]\n");
|
||||
else printf("Insercao retornou false (5).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 6, true);
|
||||
if(res) printf("Insercao retornou true (6). [OK]\n");
|
||||
else printf("Insercao retornou false (6).\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
printf("################# ATENDENDO ####################### ----- 2\n");
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (2), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (2).\n");
|
||||
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (3), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (3).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (4), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (4).\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = atenderPrimeiraDaFila(f, &id);
|
||||
if(res) printf("Atendimento retornou true (5), id=%i. [OK]\n",id);
|
||||
else printf("Atendimento retornou false (5).\n");
|
||||
|
||||
printf("################# INSERINDO PARTE 2 ############### ----- 1\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 7, true);
|
||||
if(res) printf("Insercao retornou true (7). [OK]\n");
|
||||
else printf("Insercao retornou false (7).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 8, false);
|
||||
if(res) printf("Insercao retornou true (8). [OK]\n");
|
||||
else printf("Insercao retornou false (8).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 11, false);
|
||||
if(res) printf("Insercao retornou true (7). [OK]\n");
|
||||
else printf("Insercao retornou false (7).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 9, true);
|
||||
if(res) printf("Insercao retornou true (9). [OK]\n");
|
||||
else printf("Insercao retornou false (9).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 10, false);
|
||||
if(res) printf("Insercao retornou true (10). [OK]\n");
|
||||
else printf("Insercao retornou false (10).\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
printf("################# SAINDO DA FILA ################## ----- 2\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 8);
|
||||
if(res) printf("Desistindo da fila retornou true (2).\n");
|
||||
else printf("Desistindo da fila retornou false (2). [OK]\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 10);
|
||||
if(res) printf("Desistindo da fila retornou true (3). [OK]\n");
|
||||
else printf("Desistindo da fila retornou false (3).\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 7);
|
||||
if(res) printf("Desistindo da fila retornou true (4). [OK]\n");
|
||||
else printf("Desistindo da fila retornou false (4).\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 11);
|
||||
if(res) printf("Desistindo da fila retornou true (2).\n");
|
||||
else printf("Desistindo da fila retornou false (2). [OK]\n");
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 9);
|
||||
if(res) printf("Desistindo da fila retornou true (5). [OK]\n");
|
||||
else printf("Desistindo da fila retornou false (5).\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("################# INSERINDO ####################### ---- 3\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 5, true);
|
||||
if(res) printf("Insercao retornou true (5). [OK]\n");
|
||||
else printf("Insercao retornou false (5).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 6, true);
|
||||
if(res) printf("Insercao retornou true (6). [OK]\n");
|
||||
else printf("Insercao retornou false (6).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 4, false);
|
||||
if(res) printf("Insercao retornou true (5). [OK]\n");
|
||||
else printf("Insercao retornou false (5).\n");
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 9, false);
|
||||
if(res) printf("Insercao retornou true (6). [OK]\n");
|
||||
else printf("Insercao retornou false (6).\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("################# SAINDO DA FILA ################## ----- 2\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = desistirDaFila(f, 4);
|
||||
if(res) printf("Desistindo da fila retornou true (2).\n");
|
||||
else printf("Desistindo da fila retornou false (2). [OK]\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("################# INSERINDO ####################### ---- 3\n");
|
||||
|
||||
exibirLog(f);
|
||||
res = inserirPessoaNaFila(f, 33, true);
|
||||
if(res) printf("Insercao retornou true (5). [OK]\n");
|
||||
else printf("Insercao retornou false (5).\n");
|
||||
exibirLog(f);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,150 @@
|
|||
/*********************************************************************/
|
||||
/** ACH2023 - Algoritmos e Estruturas de Dados I **/
|
||||
/** EACH-USP - Segundo Semestre de 2021 **/
|
||||
/** 04 - Prof. Luciano Antonio Digiampietri **/
|
||||
/** **/
|
||||
/** EP3 - Fila de Prioridade (utilizando heap) **/
|
||||
/** **/
|
||||
/** Guilherme de Abreu Barreto nUSP: 12543033 **/
|
||||
/** **/
|
||||
/*********************************************************************/
|
||||
|
||||
#include "filaDePrioridade.h"
|
||||
#define MAX 5
|
||||
|
||||
PFILA criarFila(){
|
||||
PFILA res = (PFILA) malloc(sizeof(FILADEPRIORIDADE));
|
||||
res->referencias = (PONT*) malloc(sizeof(PONT)*MAX);
|
||||
res->heap = (PONT*) malloc(sizeof(PONT)*MAX);
|
||||
int i;
|
||||
for (i=0; i<MAX; i++) {
|
||||
res->referencias[i] = NULL;
|
||||
res->heap[i] = NULL;
|
||||
}
|
||||
res->elementosNoHeap = 0;
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
bool exibirLog(PFILA f){
|
||||
printf("Log [elementos: %i]\n", f->elementosNoHeap);
|
||||
PONT atual;
|
||||
int i;
|
||||
for (i=0; i<f->elementosNoHeap; i++) {
|
||||
atual = f->heap[i];
|
||||
printf("[%i;%f;%i] ", atual->id, atual->prioridade, atual->posicao);
|
||||
}
|
||||
printf("\n\n");
|
||||
}
|
||||
|
||||
/* Funções auxiliares */
|
||||
|
||||
PONT novoElemento (int id, int posicao, float prioridade) {
|
||||
PONT novo = malloc (sizeof(ELEMENTO));
|
||||
|
||||
novo->id = id;
|
||||
novo->prioridade = prioridade;
|
||||
novo->posicao = posicao;
|
||||
return novo;
|
||||
}
|
||||
|
||||
void troca (PONT *a, PONT *b) {
|
||||
PONT tmp = *a;
|
||||
int posicao = tmp->posicao;
|
||||
|
||||
(*a)->posicao = (*b)->posicao;
|
||||
(*b)->posicao = posicao;
|
||||
*a = *b;
|
||||
*b = tmp;
|
||||
}
|
||||
|
||||
void subirNoHeap(PFILA f, PONT atual) {
|
||||
int pai;
|
||||
|
||||
if (atual->posicao == 0)
|
||||
return;
|
||||
pai = (atual->posicao - 1) / 2;
|
||||
if (f->heap[pai]->prioridade >= atual->prioridade)
|
||||
return;
|
||||
troca(&f->heap[pai], &f->heap[atual->posicao]);
|
||||
subirNoHeap(f, f->heap[pai]);
|
||||
}
|
||||
|
||||
void descerNoHeap(PFILA f, PONT atual) {
|
||||
int max = atual->posicao, esq = 2 * max + 1, dir = esq + 1;
|
||||
|
||||
if (esq >= f->elementosNoHeap)
|
||||
return;
|
||||
if (f->heap[esq]->prioridade > f->heap[max]->prioridade)
|
||||
max = esq;
|
||||
if (dir < f->elementosNoHeap && f->heap[dir]->prioridade > f->heap[max]->prioridade)
|
||||
max = dir;
|
||||
if (max == atual->posicao)
|
||||
return;
|
||||
|
||||
troca(&f->heap[max], &f->heap[atual->posicao]);
|
||||
descerNoHeap(f, f->heap[max]);
|
||||
}
|
||||
|
||||
void adicionarNaFila (PFILA f, PONT novo) {
|
||||
f->referencias[novo->id] = novo;
|
||||
f->heap[novo->posicao] = novo;
|
||||
f->elementosNoHeap++;
|
||||
subirNoHeap(f, novo);
|
||||
}
|
||||
|
||||
void removerDaFila (PFILA f, PONT remover) {
|
||||
f->referencias[remover->id] = NULL;
|
||||
f->heap[0] = f->heap[--f->elementosNoHeap];
|
||||
f->heap[f->elementosNoHeap] = NULL;
|
||||
if (!f->heap[0])
|
||||
return;
|
||||
f->heap[0]->posicao = 0;
|
||||
descerNoHeap(f, f->heap[0]);
|
||||
}
|
||||
|
||||
/* Funções principais */
|
||||
|
||||
int tamanho(PFILA f){
|
||||
return f->elementosNoHeap;
|
||||
}
|
||||
|
||||
bool inserirElemento(PFILA f, int id, float prioridade){
|
||||
if (!f || id < 0 || id >= MAX || f->referencias[id])
|
||||
return false;
|
||||
adicionarNaFila(f, novoElemento(id, f->elementosNoHeap, prioridade));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool aumentarPrioridade(PFILA f, int id, float novaPrioridade){
|
||||
if (!f || id < 0 || id >= MAX || !f->referencias[id]
|
||||
|| f->referencias[id]->prioridade >= novaPrioridade)
|
||||
return false;
|
||||
f->referencias[id]->prioridade = novaPrioridade;
|
||||
subirNoHeap(f, f->referencias[id]);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool reduzirPrioridade(PFILA f, int id, float novaPrioridade){
|
||||
if (!f || id < 0 || id >= MAX || !f->referencias[id]
|
||||
|| f->referencias[id]->prioridade < novaPrioridade)
|
||||
return false;
|
||||
f->referencias[id]->prioridade = novaPrioridade;
|
||||
descerNoHeap(f, f->referencias[id]);
|
||||
return true;
|
||||
}
|
||||
|
||||
PONT removerElemento(PFILA f){
|
||||
PONT remover = (f) ? f->heap[0] : NULL;
|
||||
|
||||
if (remover)
|
||||
removerDaFila(f, remover);
|
||||
return remover;
|
||||
}
|
||||
|
||||
bool consultarPrioridade(PFILA f, int id, float* resposta){
|
||||
if (!f || id < 0 || id >= MAX || !f->referencias[id])
|
||||
return false;
|
||||
*resposta = f->referencias[id]->prioridade;
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,151 @@
|
|||
/*********************************************************************/
|
||||
/** ACH2023 - Algoritmos e Estruturas de Dados I **/
|
||||
/** EACH-USP - Segundo Semestre de 2021 **/
|
||||
/** 04 - Prof. Luciano Antonio Digiampietri **/
|
||||
/** **/
|
||||
/** EP3 - Fila de Prioridade (utilizando heap) **/
|
||||
/** **/
|
||||
/** Guilherme de Abreu Barreto nUSP: 12543033 **/
|
||||
/** **/
|
||||
/*********************************************************************/
|
||||
|
||||
#include "filaDePrioridade.h"
|
||||
#define MAX 5
|
||||
|
||||
PFILA criarFila(){
|
||||
PFILA res = (PFILA) malloc(sizeof(FILADEPRIORIDADE));
|
||||
res->referencias = (PONT*) malloc(sizeof(PONT)*MAX);
|
||||
res->heap = (PONT*) malloc(sizeof(PONT)*MAX);
|
||||
int i;
|
||||
for (i=0; i<MAX; i++) {
|
||||
res->referencias[i] = NULL;
|
||||
res->heap[i] = NULL;
|
||||
}
|
||||
res->elementosNoHeap = 0;
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
bool exibirLog(PFILA f){
|
||||
printf("Log [elementos: %i]\n", f->elementosNoHeap);
|
||||
PONT atual;
|
||||
int i;
|
||||
for (i=0; i<f->elementosNoHeap; i++) {
|
||||
atual = f->heap[i];
|
||||
printf("[%i;%f;%i] ", atual->id, atual->prioridade, atual->posicao);
|
||||
}
|
||||
printf("\n\n");
|
||||
}
|
||||
|
||||
/* Funções auxiliares */
|
||||
|
||||
PONT novoElemento (int id, int posicao, float prioridade) {
|
||||
PONT novo = malloc (sizeof(ELEMENTO));
|
||||
|
||||
novo->id = id;
|
||||
novo->prioridade = prioridade;
|
||||
novo->posicao = posicao;
|
||||
return novo;
|
||||
}
|
||||
|
||||
void troca (PONT *a, PONT *b) {
|
||||
PONT tmp = *a;
|
||||
int posicao = tmp->posicao;
|
||||
|
||||
(*a)->posicao = (*b)->posicao;
|
||||
(*b)->posicao = posicao;
|
||||
*a = *b;
|
||||
*b = tmp;
|
||||
}
|
||||
|
||||
void subirNoHeap(PFILA f, PONT atual) {
|
||||
int pai;
|
||||
|
||||
if (atual->posicao == 0)
|
||||
return;
|
||||
pai = (atual->posicao - 1) / 2;
|
||||
if (f->heap[pai]->prioridade >= atual->prioridade)
|
||||
return;
|
||||
|
||||
troca(&f->heap[pai], &f->heap[atual->posicao]);
|
||||
subirNoHeap(f, f->heap[pai]);
|
||||
}
|
||||
|
||||
void descerNoHeap(PFILA f, PONT atual) {
|
||||
int max = atual->posicao, esq = 2 * max + 1, dir = esq + 1;
|
||||
|
||||
if (esq >= f->elementosNoHeap)
|
||||
return;
|
||||
if (f->heap[esq]->prioridade > f->heap[max]->prioridade)
|
||||
max = esq;
|
||||
if (dir < f->elementosNoHeap && f->heap[dir]->prioridade > f->heap[max]->prioridade)
|
||||
max = dir;
|
||||
else if (max == atual->posicao)
|
||||
return;
|
||||
|
||||
troca(&f->heap[max], &f->heap[atual->posicao]);
|
||||
descerNoHeap(f, f->heap[max]);
|
||||
}
|
||||
|
||||
void adicionarNaFila (PFILA f, PONT novo) {
|
||||
f->referencias[novo->id] = novo;
|
||||
f->heap[novo->posicao] = novo;
|
||||
f->elementosNoHeap++;
|
||||
subirNoHeap(f, novo);
|
||||
}
|
||||
|
||||
void removerDaFila (PFILA f, PONT remover) {
|
||||
f->referencias[remover->id] = NULL;
|
||||
f->heap[0] = f->heap[--f->elementosNoHeap];
|
||||
f->heap[f->elementosNoHeap] = NULL;
|
||||
if (!f->heap[0])
|
||||
return;
|
||||
f->heap[0]->posicao = 0;
|
||||
descerNoHeap(f, f->heap[0]);
|
||||
}
|
||||
|
||||
/* Funções principais */
|
||||
|
||||
int tamanho(PFILA f){
|
||||
return (f) ? f->elementosNoHeap : 0;
|
||||
}
|
||||
|
||||
bool inserirElemento(PFILA f, int id, float prioridade){
|
||||
if (!f || id < 0 || id >= MAX || f->referencias[id])
|
||||
return false;
|
||||
adicionarNaFila(f, novoElemento(id, f->elementosNoHeap, prioridade));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool aumentarPrioridade(PFILA f, int id, float novaPrioridade){
|
||||
if (!f || id < 0 || id >= MAX || !f->referencias[id]
|
||||
|| f->referencias[id]->prioridade >= novaPrioridade)
|
||||
return false;
|
||||
f->referencias[id]->prioridade = novaPrioridade;
|
||||
subirNoHeap(f, f->referencias[id]);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool reduzirPrioridade(PFILA f, int id, float novaPrioridade){
|
||||
if (!f || id < 0 || id >= MAX || !f->referencias[id]
|
||||
|| f->referencias[id]->prioridade < novaPrioridade)
|
||||
return false;
|
||||
f->referencias[id]->prioridade = novaPrioridade;
|
||||
descerNoHeap(f, f->referencias[id]);
|
||||
return true;
|
||||
}
|
||||
|
||||
PONT removerElemento(PFILA f){
|
||||
PONT remover = (f) ? f->heap[0] : NULL;
|
||||
|
||||
if (remover)
|
||||
removerDaFila(f, remover);
|
||||
return remover;
|
||||
}
|
||||
|
||||
bool consultarPrioridade(PFILA f, int id, float* resposta){
|
||||
if (!f || id < 0 || id >= MAX || !f->referencias[id])
|
||||
return false;
|
||||
*resposta = f->referencias[id]->prioridade;
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
#include "filaDePrioridade.c"
|
||||
|
||||
int main() {
|
||||
PFILA f = criarFila();
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 1, 1)) printf("ok\n");
|
||||
else printf("nok (1)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 3, 3)) printf("ok\n");
|
||||
else printf("nok (2)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 2, 2)) printf("ok\n");
|
||||
else printf("nok (3)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 0, 0)) printf("ok\n");
|
||||
else printf("nok (4)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 5, 5)) printf("ok\n");
|
||||
else printf("nok (5)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 5, 10)) printf("ok\n");
|
||||
else printf("nok (6)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 0, 15)) printf("ok\n");
|
||||
else printf("nok (7)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 3, 4)) printf("ok\n");
|
||||
else printf("nok (8)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 3, 4)) printf("ok\n");
|
||||
else printf("nok (9) - esperado, pois a nova prioridade nao eh maior\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 4, 4)) printf("ok\n");
|
||||
else printf("nok (10) - esperado, elemento com id=4 nao existe\n");
|
||||
exibirLog(f);
|
||||
|
||||
PONT prioritario;
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia (1)\n");
|
||||
exibirLog(f);
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia (2)\n");
|
||||
exibirLog(f);
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia (3)\n");
|
||||
exibirLog(f);
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia (4)\n");
|
||||
exibirLog(f);
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia (5)\n");
|
||||
exibirLog(f);
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia (6)\n");
|
||||
exibirLog(f);
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia (7)\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 1, 1)) printf("ok\n");
|
||||
else printf("nok (10)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 3, 3)) printf("ok\n");
|
||||
else printf("nok (11)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 2, 2)) printf("ok\n");
|
||||
else printf("nok (12)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 0, 0.5)) printf("ok\n");
|
||||
else printf("nok (13)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 5, 5)) printf("ok\n");
|
||||
else printf("nok (14)\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("\n\nReduzindo prioridade\n");
|
||||
|
||||
|
||||
if(reduzirPrioridade(f, 5, 0)) printf("ok\n");
|
||||
else printf("nok (15)\n");
|
||||
exibirLog(f);
|
||||
if(reduzirPrioridade(f, 0, 1)) printf("ok\n");
|
||||
else printf("nok (16) - esperado, nova prioridade eh maior\n");
|
||||
exibirLog(f);
|
||||
if(reduzirPrioridade(f, 3, 2)) printf("ok\n");
|
||||
else printf("nok (17)\n");
|
||||
exibirLog(f);
|
||||
if(reduzirPrioridade(f, 3, 1.5)) printf("ok\n");
|
||||
else printf("nok (18) - esperado, nova prioridade eh igual\n");
|
||||
exibirLog(f);
|
||||
if(reduzirPrioridade(f, 4, 1)) printf("ok\n");
|
||||
else printf("nok (19) - esperado, elemento com id=4 nao existe\n");
|
||||
exibirLog(f);
|
||||
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
#include "filaDePrioridade.c"
|
||||
|
||||
int main() {
|
||||
int i;
|
||||
float resposta;
|
||||
|
||||
PFILA f = criarFila();
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 1, 1)) printf("ok\n");
|
||||
else printf("nok (1)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 3, 3)) printf("ok\n");
|
||||
else printf("nok (2)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 2, 2)) printf("ok\n");
|
||||
else printf("nok (3)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 0, 0)) printf("ok\n");
|
||||
else printf("nok (4)\n");
|
||||
exibirLog(f);
|
||||
if(inserirElemento(f, 5, 5)) printf("ok\n");
|
||||
else printf("nok (5)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 5, 10)) printf("ok\n");
|
||||
else printf("nok (6)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 0, 15)) printf("ok\n");
|
||||
else printf("nok (7)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 3, 4)) printf("ok\n");
|
||||
else printf("nok (8)\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 3, 4)) printf("ok\n");
|
||||
else printf("nok (9) - esperado, pois a nova prioridade nao eh maior\n");
|
||||
exibirLog(f);
|
||||
if(aumentarPrioridade(f, 4, 4)) printf("ok\n");
|
||||
else printf("nok (10) - esperado, elemento com id=4 nao existe\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("Tamanho: %d\n", tamanho(f));
|
||||
printf("Prioridade de cada elemento nas referências:\n");
|
||||
for (i = 0; i < MAX; i++)
|
||||
if (f->heap[i]) {
|
||||
consultarPrioridade(f, i, &resposta);
|
||||
printf("id: %d, posição no heap: %d, prioridade: %f\n", i, f->referencias[i]->posicao, resposta);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
#include "filaDePrioridade.c"
|
||||
|
||||
int main() {
|
||||
PFILA f = criarFila();
|
||||
int i;
|
||||
float resposta;
|
||||
|
||||
if(inserirElemento(f, 0, 5)) printf("\nI: ok -- 1\n");
|
||||
else printf("nok -- 1\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 1, 10)) printf("I: ok -- 2\n");
|
||||
else printf("nok -- 2\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 2, 15)) printf("I: ok -- 3\n");
|
||||
else printf("nok -- 3\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 3, 8)) printf("I: ok -- 4\n");
|
||||
else printf("nok -- 4\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 4, 12)) printf("I: ok -- 5\n");
|
||||
else printf("nok -- 5\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(aumentarPrioridade(f, 3, 14)) printf("A: ok -- 6\n");
|
||||
else printf("nok -- 6\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(aumentarPrioridade(f, 4, 30)) printf("A: ok -- 7\n");
|
||||
else printf("nok -- 7\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(tamanho(f)) printf("\nVerificando Tamanho | ok -- 8\n");
|
||||
else printf("nok -- 8\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(aumentarPrioridade(f, 0, 29)) printf("A: ok -- 9\n");
|
||||
else printf("nok -- 9\n");
|
||||
exibirLog(f);
|
||||
|
||||
PONT prioritario;
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Rm: ok -- 10 - Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 4, 25)) printf("I: ok -- 11\n");
|
||||
else printf("nok -- 11\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 4, 12)) printf("I: ok -- 12\n");
|
||||
else printf("nok -- 12\n");
|
||||
exibirLog(f);
|
||||
|
||||
printf("Consultando todas as prioridades -- 13\n");
|
||||
for (i = 0; i < MAX; i++)
|
||||
if (f->heap[i]) {
|
||||
consultarPrioridade(f, i, &resposta);
|
||||
printf("id: %d, posição no heap: %d, prioridade: %f\n", i, f->referencias[i]->posicao, resposta);
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
if(reduzirPrioridade(f, 0, 5)) printf("Rd: ok -- 14\n");
|
||||
else printf("nok -- 14\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(reduzirPrioridade(f, 4, 11)) printf("Rd: ok -- 15\n");
|
||||
else printf("nok -- 15\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(reduzirPrioridade(f, 1, 1)) printf("Rd: ok -- 16\n");
|
||||
else printf("nok -- 16\n");
|
||||
exibirLog(f);
|
||||
|
||||
prioritario = removerElemento(f);
|
||||
if (prioritario) printf("Rm: ok -- 17 - Prioritario: %i, %f\n", prioritario->id, prioritario->prioridade);
|
||||
else printf("Fila vazia\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(aumentarPrioridade(f, 0, 20)) printf("A: ok -- 18\n");
|
||||
else printf("nok -- 18\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(aumentarPrioridade(f, 4, 19)) printf("A: ok -- 19\n");
|
||||
else printf("nok -- 19\n");
|
||||
exibirLog(f);
|
||||
|
||||
if(inserirElemento(f, 2, 18)) printf("I: ok -- 20\n");
|
||||
else printf("nok -- 20\n");
|
||||
exibirLog(f);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
#include <stdio.h>
|
||||
|
||||
int main() {
|
||||
long long int nusp;
|
||||
printf("Digite seu número USP: ");
|
||||
scanf("%lld", &nusp);
|
||||
|
||||
printf("Imprimindo inteiro: %lli\n", nusp);
|
||||
printf("Imprimindo numero: %lld\n", nusp);
|
||||
printf("Imprimindo float (com cast): %f\n", (float) nusp);
|
||||
printf("Imprimindo quociente: %lli\n", nusp/2);
|
||||
printf("Imprimindo resto: %lld\n", nusp%2);
|
||||
printf("Imprimindo quadrado: %lld\n", nusp*nusp);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct pessoa {
|
||||
int id;
|
||||
struct pessoa * mae, * pai;
|
||||
} Pessoa;
|
||||
|
||||
Pessoa * inicializar (int id) {
|
||||
Pessoa * init = malloc(sizeof(*init));
|
||||
init->id = id;
|
||||
init->mae = init->pai = NULL;
|
||||
return init;
|
||||
}
|
||||
|
||||
void registrar(Pessoa * filho, Pessoa * mae, Pessoa * pai) {
|
||||
filho->mae = mae;
|
||||
filho->pai = pai;
|
||||
}
|
|
@ -0,0 +1,255 @@
|
|||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#define array int *
|
||||
|
||||
bool isSorted(array A, int size) {
|
||||
if (size <= 1)
|
||||
return true;
|
||||
if (*A > *(A + 1))
|
||||
return false;
|
||||
return isSorted(A + 1, size - 1);
|
||||
}
|
||||
|
||||
/* Bubble Sort */
|
||||
|
||||
void swap(int *a, int *b) {
|
||||
int tmp = *a;
|
||||
*a = *b;
|
||||
*b = tmp;
|
||||
}
|
||||
|
||||
void bubbleSort(array A, int size) {
|
||||
int i;
|
||||
|
||||
if (size-- <= 1)
|
||||
return;
|
||||
for (i = 0; i < size; i++)
|
||||
if (A[i] > A[i + 1])
|
||||
swap(&A[i], &A[i + 1]);
|
||||
bubbleSort(A, size);
|
||||
}
|
||||
|
||||
/* Selection Sort */
|
||||
|
||||
int *minimalValue(array A, int size) {
|
||||
int i, pos = 0;
|
||||
|
||||
for (i = 1; i < size; i++)
|
||||
if (A[i] < A[pos])
|
||||
pos = i;
|
||||
return A + pos;
|
||||
}
|
||||
|
||||
void selectionSort(array A, int size) {
|
||||
if (size <= 1)
|
||||
return;
|
||||
swap(A, minimalValue(A, size));
|
||||
selectionSort(A + 1, size - 1);
|
||||
}
|
||||
|
||||
/* Insertion Sort */
|
||||
|
||||
void insertionSort(array A, int size) {
|
||||
int i, tmp;
|
||||
|
||||
if (size-- <= 1)
|
||||
return;
|
||||
insertionSort(A, size);
|
||||
tmp = A[size];
|
||||
for (i = size; i > 0 && A[i - 1] > tmp; i--)
|
||||
A[i] = A[i - 1];
|
||||
A[i] = tmp;
|
||||
}
|
||||
|
||||
/* Shell sort */
|
||||
|
||||
void insertionSortMod(array A, int size, int start, int gap) {
|
||||
int i = start + gap, tmp;
|
||||
|
||||
if (i >= size)
|
||||
return;
|
||||
tmp = A[i];
|
||||
while (i >= gap && A[i - gap] > tmp) {
|
||||
A[i] = A[i - gap];
|
||||
i -= gap;
|
||||
}
|
||||
A[i] = tmp;
|
||||
insertionSortMod(A, size, start + gap, gap);
|
||||
}
|
||||
|
||||
void shellSort(array A, int size) {
|
||||
int i, sublist_lenght;
|
||||
|
||||
for (sublist_lenght = size / 2; sublist_lenght > 0; sublist_lenght /= 2)
|
||||
for (i = 0; i < sublist_lenght; i++)
|
||||
insertionSortMod(A, size, i, sublist_lenght);
|
||||
}
|
||||
|
||||
/* Merge Sort */
|
||||
|
||||
void merge(array A, int pivot, int size) {
|
||||
int i, k, j = pivot;
|
||||
array tmp = malloc(size * sizeof(int));
|
||||
|
||||
for (i = k = 0; k < size; k++)
|
||||
tmp[k] = (j == size || (i < pivot && A[i] <= A[j])) ? A[i++] : A[j++];
|
||||
for (k = 0; k < size; k++)
|
||||
A[k] = tmp[k];
|
||||
free(tmp);
|
||||
}
|
||||
|
||||
/* Merge function using a watchdog to check for the limits of the array. One
|
||||
less comparison is made per loop and thus this is a faster version.
|
||||
|
||||
void merge(array A, int pivot, int size) {
|
||||
int i = 0, j = size - 1, k; array tmp = malloc(size * sizeof(int));
|
||||
|
||||
while (i < pivot) {
|
||||
tmp[i] = A[i];
|
||||
i++;
|
||||
}
|
||||
while (i < size) {
|
||||
tmp[i] = A[j - (i - pivot)];
|
||||
i++;
|
||||
}
|
||||
for (i = k = 0; k < size; k++)
|
||||
A[k] = (tmp[i] <= tmp[j]) ? tmp[i++] : tmp[j--];
|
||||
free(tmp);
|
||||
}
|
||||
*/
|
||||
|
||||
void mergeSort(array A, int size) {
|
||||
int pivot;
|
||||
|
||||
if (size <= 1)
|
||||
return;
|
||||
pivot = size / 2;
|
||||
mergeSort(A, pivot);
|
||||
mergeSort(A + pivot, size - pivot);
|
||||
merge(A, pivot, size);
|
||||
}
|
||||
|
||||
/* Quick Sort */
|
||||
|
||||
int *median(int *a, int *b, int *c) {
|
||||
if ((*a > *b) ^ (*a > *c))
|
||||
return a;
|
||||
if ((*b < *a) ^ (*b < *c))
|
||||
return b;
|
||||
return c;
|
||||
}
|
||||
|
||||
int partition(array A, int size) {
|
||||
int i, j, last = size - 1;
|
||||
|
||||
swap(A + last, median(A, A + size / 2, A + last));
|
||||
for (i = j = 0; i < last; i++)
|
||||
if (A[i] <= A[last])
|
||||
swap(&A[i], &A[j++]);
|
||||
swap(A + i, A + j);
|
||||
return j;
|
||||
}
|
||||
|
||||
void quickSort(array A, int size) {
|
||||
int pivot;
|
||||
|
||||
if (size <= 1)
|
||||
return;
|
||||
pivot = partition(A, size);
|
||||
quickSort(A, pivot++);
|
||||
quickSort(A + pivot, size - pivot);
|
||||
}
|
||||
|
||||
/* Heap Sort */
|
||||
|
||||
void heapify(array A, int size, int i) {
|
||||
int max = i, left = 2 * max + 1, right = left + 1;
|
||||
|
||||
if (left >= size)
|
||||
return;
|
||||
if (A[left] > A[max])
|
||||
max = left;
|
||||
if (right < size && A[right] > A[max])
|
||||
max = right;
|
||||
else if (max == i)
|
||||
return;
|
||||
|
||||
swap(A + i, A + max);
|
||||
heapify(A, size, max);
|
||||
}
|
||||
|
||||
void heapSort(array A, int size) {
|
||||
int i;
|
||||
|
||||
if (size <= 1)
|
||||
return;
|
||||
|
||||
for (i = (size - 1) / 2; i <= 0; i--)
|
||||
heapify(A, size, i);
|
||||
|
||||
for (i = size - 1; i > 0; i--) {
|
||||
swap(A, A + i);
|
||||
heapify(A, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Counting Sort */
|
||||
|
||||
array cumulativeFrequency(array A, int size, int max) {
|
||||
int i;
|
||||
array frequency = calloc((max + 1), sizeof(int));
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
frequency[A[i] + 1]++;
|
||||
for (i = 1; i <= max; i++)
|
||||
frequency[i] += frequency[i - 1];
|
||||
return frequency;
|
||||
}
|
||||
|
||||
void countingSort(array *A, int size, int max) {
|
||||
int i;
|
||||
array count = cumulativeFrequency(*A, size, max);
|
||||
array sorted = malloc(size * sizeof(int));
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
sorted[count[(*A)[i]]++] = (*A)[i];
|
||||
free(*A);
|
||||
free(count);
|
||||
*A = sorted;
|
||||
}
|
||||
|
||||
/* Radix Sort */
|
||||
|
||||
array cumulativeFreq(array A, int size, int exp) {
|
||||
int i, radix;
|
||||
array frequency = calloc(19, sizeof(int));
|
||||
|
||||
for (i = 0; i < size; i++) {
|
||||
radix = A[i] / exp % 10;
|
||||
frequency[10 + radix]++;
|
||||
}
|
||||
for (i = 1; i < 18; i++)
|
||||
frequency[i] += frequency[i - 1];
|
||||
return frequency;
|
||||
}
|
||||
|
||||
void countingSortMod(array *A, int size, int exp) {
|
||||
int i, radix;
|
||||
array count = cumulativeFreq(*A, size, exp);
|
||||
array sorted = malloc(size * sizeof(int));
|
||||
|
||||
for (i = 0; i < size; i++) {
|
||||
radix = (*A)[i] / exp % 10;
|
||||
sorted[count[9 + radix]++] = (*A)[i];
|
||||
}
|
||||
free(*A);
|
||||
free(count);
|
||||
*A = sorted;
|
||||
}
|
||||
|
||||
void radixSort(array *A, int size, int max) {
|
||||
int exp;
|
||||
|
||||
for (exp = 1; max / exp > 0; exp *= 10)
|
||||
countingSortMod(A, size, exp);
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *next, *prev;
|
||||
} Node;
|
||||
|
||||
typedef struct {
|
||||
int size;
|
||||
Node *front, *rear;
|
||||
} Deque;
|
||||
|
||||
typedef enum {front, rear} End;
|
||||
|
||||
void push (Deque *q, int value, End e) {
|
||||
Node *n = malloc(sizeof(Node));
|
||||
|
||||
n->value = value;
|
||||
if (e == front) {
|
||||
n->next = q->front;
|
||||
n->prev = NULL;
|
||||
q->front->prev = n;
|
||||
q->front = n;
|
||||
}
|
||||
else {
|
||||
n->prev = q->rear;
|
||||
n->next = NULL;
|
||||
q->rear->next = n;
|
||||
q->rear = n;
|
||||
}
|
||||
q->size++;
|
||||
}
|
||||
|
||||
int pop (Deque *q, End e) {
|
||||
int value;
|
||||
Node *n;
|
||||
|
||||
if (q->size == 0)
|
||||
return EOF;
|
||||
if (e == front) {
|
||||
n = q->front;
|
||||
q->front = n->next;
|
||||
q->front->prev = NULL;
|
||||
}
|
||||
else {
|
||||
n = q->rear;
|
||||
q->rear = n->prev;
|
||||
q->rear->next = NULL;
|
||||
}
|
||||
value = n->value;
|
||||
free(n);
|
||||
q->size--;
|
||||
return value;
|
||||
}
|
||||
|
||||
int peek (Deque *q, End e) {
|
||||
if (q->size == 0)
|
||||
return EOF;
|
||||
if (e == front)
|
||||
return q->front->value;
|
||||
return q->rear->value;
|
||||
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *prev, *next;
|
||||
} Node;
|
||||
|
||||
typedef struct {
|
||||
Node *start, *end;
|
||||
} List;
|
||||
|
||||
void insertIn (List *l, int value) {
|
||||
Node *prev = NULL, *current, *next;
|
||||
|
||||
for (next = l->start; next && next->value < value; next = next->next)
|
||||
prev = next;
|
||||
if (next && next->value == value)
|
||||
return;
|
||||
|
||||
current = malloc(sizeof(*current));
|
||||
current->value = value;
|
||||
current->prev = prev;
|
||||
current->next = next;
|
||||
|
||||
if (prev)
|
||||
l->start = current;
|
||||
else
|
||||
prev->next = current;
|
||||
|
||||
if (next)
|
||||
l->end = current;
|
||||
else
|
||||
next->prev = current;
|
||||
}
|
||||
|
||||
void removeFrom (List *l, int value) {
|
||||
Node *current = l->start;
|
||||
|
||||
while (current && current->value < value)
|
||||
current = current->next;
|
||||
if (!current)
|
||||
return;
|
||||
|
||||
if (current->prev && current->next) {
|
||||
current->prev->next = current->next;
|
||||
current->next->prev = current->prev;
|
||||
}
|
||||
else if (!current->prev) {
|
||||
l->start = current->next;
|
||||
if (current->next)
|
||||
current->next->prev = NULL;
|
||||
}
|
||||
else {
|
||||
l->end = current->prev;
|
||||
if (current->prev)
|
||||
current->prev->next = NULL;
|
||||
}
|
||||
free(current);
|
||||
}
|
||||
|
||||
void printList (List l) {
|
||||
int i;
|
||||
Node *current = l.start;
|
||||
|
||||
for (i = 0; current; i++) {
|
||||
printf("\nÍndice: %-6d Valor: %-6d (Endereços) Anterior: %p Atual: %p Próximo: %p\n", i, current->value, current->prev, current, current->next);
|
||||
current = current->next;
|
||||
}
|
||||
}
|
||||
|
||||
int main () {
|
||||
int i;
|
||||
char c;
|
||||
List l = {0};
|
||||
|
||||
printf("Este programa adiciona valores inteiros à uma lista duplamente ligada, e depois permite excluí-los da mesma.\nDigite uma sequência de valores e pressione ENTER: ");
|
||||
do {
|
||||
if(!scanf("%d%c", &i, &c)) {
|
||||
printf("Valor inválido detectado.");
|
||||
return 1;
|
||||
}
|
||||
insertIn(&l, i);
|
||||
} while (c != '\n');
|
||||
printList(l);
|
||||
|
||||
printf("\nDigite uma sequência de valores a serem apagados e pressione ENTER: ");
|
||||
do {
|
||||
if(!scanf("%d%c", &i, &c)) {
|
||||
printf("Valor inválido detectado.");
|
||||
return 1;
|
||||
}
|
||||
removeFrom(&l, i);
|
||||
} while (c != '\n');
|
||||
printList(l);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct item {
|
||||
int value;
|
||||
struct item * next;
|
||||
} Item;
|
||||
|
||||
typedef struct {
|
||||
Item * start;
|
||||
} List;
|
||||
|
||||
int listSize (List * l) {
|
||||
int size;
|
||||
Item * index = l->start;
|
||||
|
||||
for (size = 0; index; size++)
|
||||
index = index->next;
|
||||
return size;
|
||||
}
|
||||
|
||||
Item * findInOrderedList (int value, List * l) {
|
||||
Item * index = l->start;
|
||||
|
||||
while (index && index->value < value)
|
||||
index = index->next;
|
||||
|
||||
return (index && index->value == value) ? index : NULL;
|
||||
}
|
||||
|
||||
/* The existance of these redundant functions is probably not a good sign */
|
||||
|
||||
Item * findInOrderedListAux (int value, List * l, Item ** prev) {
|
||||
Item * index = l->start;
|
||||
|
||||
*prev = NULL;
|
||||
while (!index && index->value < value){
|
||||
*prev = index;
|
||||
index = index->next;
|
||||
}
|
||||
return (index && index->value == value) ? index : NULL;
|
||||
}
|
||||
|
||||
bool insertInOrderedList (int value, List * l) {
|
||||
Item * prev;
|
||||
Item * i = findInOrderedListAux(value, l, &prev);
|
||||
|
||||
if (i)
|
||||
return false;
|
||||
|
||||
i = malloc(sizeof(Item));
|
||||
i->value = value;
|
||||
|
||||
if (prev) {
|
||||
i->next = prev->next;
|
||||
prev->next = i;
|
||||
}
|
||||
else {
|
||||
i->next = l->start;
|
||||
l->start = i;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool removeFromOrderedList (int value, List * l) {
|
||||
Item * prev;
|
||||
Item * i = findInOrderedListAux(value, l, &prev);
|
||||
|
||||
if (!i)
|
||||
return false;
|
||||
|
||||
if (prev)
|
||||
prev->next = i->next;
|
||||
else
|
||||
l->start = i->next;
|
||||
|
||||
free(i);
|
||||
return true;
|
||||
}
|
||||
|
||||
void reinitializeList (List * l) {
|
||||
Item * prev, * i = l->start;
|
||||
|
||||
while (i) {
|
||||
prev = i;
|
||||
i = i->next;
|
||||
free(prev);
|
||||
}
|
||||
l->start = NULL;
|
||||
}
|
||||
|
||||
int main () {
|
||||
List l = {0};
|
||||
Item * index = l.start;
|
||||
|
||||
printf("Lista: \"");
|
||||
while (index) {
|
||||
printf("%i ", index->value);
|
||||
index = index->next;
|
||||
}
|
||||
printf("\"\n");
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#define MAX 50
|
||||
|
||||
typedef struct {
|
||||
int index, next;
|
||||
} Item;
|
||||
|
||||
typedef struct {
|
||||
Item a[MAX];
|
||||
int start, open;
|
||||
} List;
|
||||
|
||||
void init (List * l) {
|
||||
int i;
|
||||
|
||||
for (i = 0; i < MAX - 1; i++)
|
||||
l->a[i].next = i + 1;
|
||||
|
||||
l->a[MAX -1].next = EOF;
|
||||
l->start = EOF;
|
||||
l->open = 0;
|
||||
}
|
||||
|
||||
int listSize (List * l) {
|
||||
int i = l->start, size;
|
||||
|
||||
for (size = 0; i != EOF; size++)
|
||||
i = l->a[i].next;
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
int findInOrderedList (int k, List * l) {
|
||||
int i = l->start;
|
||||
|
||||
while (i != EOF && l->a[i].index < k)
|
||||
i = l->a[i].next;
|
||||
|
||||
if (i == EOF || l->a[i].index != k)
|
||||
return EOF;
|
||||
return i;
|
||||
}
|
||||
|
||||
int openIndex (List * l) {
|
||||
int result = l->open;
|
||||
if (l->open != EOF)
|
||||
l->open = l->a[l->open].next;
|
||||
return result;
|
||||
}
|
||||
|
||||
void returnIndex(int i, List * l) {
|
||||
l->a[i].next = l->open;
|
||||
l->open = i;
|
||||
}
|
||||
|
||||
bool insertInSortedList (Item insert, List * l) {
|
||||
if (l->open == EOF)
|
||||
return false;
|
||||
|
||||
int prev, i = l->start, k = insert.index;
|
||||
|
||||
for (prev = EOF; i != EOF && l->a[i].index < k; prev = i)
|
||||
i = l->a[i].next;
|
||||
|
||||
if (i != EOF || l->a[i].index == k)
|
||||
return false;
|
||||
|
||||
i = openIndex(l);
|
||||
l->a[i].index = k;
|
||||
|
||||
if (prev == EOF) {
|
||||
l->a[i].next = l->start;
|
||||
l->start = i;
|
||||
}
|
||||
else {
|
||||
l->a[i].next = l->a[prev].next;
|
||||
l->a[prev].next = i;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool removefromSortedList (List * l, int k) {
|
||||
int prev, i = l->start;
|
||||
|
||||
for (prev = EOF; i != EOF && l->a[i].index < k; prev = i)
|
||||
i = l->a[i].next;
|
||||
|
||||
if (i == EOF || l->a[i].index != k)
|
||||
return false;
|
||||
if (prev == EOF)
|
||||
l->start = l->a[i].next;
|
||||
else
|
||||
l->a[prev].next = l->a[i].next;
|
||||
|
||||
returnIndex(i, l);
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *prev, *next;
|
||||
} Node;
|
||||
|
||||
Node * initialize () {
|
||||
Node *n = malloc(sizeof(*n));
|
||||
|
||||
n->prev = n->next = n;
|
||||
return n;
|
||||
}
|
||||
|
||||
void reinitilize (Node * HEAD) {
|
||||
Node *current = HEAD->next;
|
||||
|
||||
while (current != HEAD) {
|
||||
current = current->next;
|
||||
free(current->prev);
|
||||
}
|
||||
current->next = current->prev = current;
|
||||
}
|
||||
|
||||
int listSize (Node *HEAD) {
|
||||
Node *current = HEAD->next;
|
||||
int size;
|
||||
|
||||
for (size = 0; current != HEAD; size++)
|
||||
current = current->next;
|
||||
return size;
|
||||
}
|
||||
|
||||
void printList (Node *HEAD) {
|
||||
Node *current = HEAD->next;
|
||||
|
||||
printf("Lista: \"");
|
||||
while (current != HEAD) {
|
||||
printf("%d ", current->value);
|
||||
current = current->next;
|
||||
}
|
||||
printf("\"\n");
|
||||
}
|
||||
|
||||
Node * findIn(Node *HEAD, int value) {
|
||||
Node *n = HEAD->next;
|
||||
HEAD->value = value;
|
||||
|
||||
while (n->value < value)
|
||||
n = n->next;
|
||||
return (n->value == value && n != HEAD) ? n : NULL;
|
||||
}
|
||||
|
||||
/* Do not use these "Ordered" implementations, thse were not well though out,
|
||||
Nonetheless I've decided to keep them as a record of the study process */
|
||||
|
||||
Node * findInOrdered(Node *HEAD, int value) {
|
||||
Node *current;
|
||||
|
||||
if (abs(value - HEAD->next->value) < abs(value - HEAD->prev->value)) {
|
||||
current = HEAD->next;
|
||||
while (current->value < value)
|
||||
current = current->next;
|
||||
}
|
||||
else {
|
||||
current = HEAD->prev;
|
||||
while (current-> value > value)
|
||||
current = current->prev;
|
||||
}
|
||||
return (current == HEAD || current->value != value) ? NULL : current;
|
||||
}
|
||||
|
||||
bool insertInOrdered(Node *HEAD, int value) {
|
||||
Node *prev, *current, *next;
|
||||
prev = next = HEAD;
|
||||
|
||||
if (abs(value - HEAD->next->value) < abs(value - HEAD->prev->value)) {
|
||||
for (next = HEAD->next; next->next != HEAD && next->value < value; next = next->next)
|
||||
prev = next;
|
||||
if (next->value == value)
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
for (prev = HEAD->prev; prev->prev != HEAD && prev->value > value; prev = prev->prev)
|
||||
next = prev;
|
||||
if (prev->value == value)
|
||||
return false;
|
||||
}
|
||||
|
||||
current = malloc(sizeof(*current));
|
||||
current->value = value;
|
||||
current->next = prev->next;
|
||||
prev->next = current;
|
||||
current->prev = next->prev;
|
||||
next->prev = current;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool insertIn(Node *HEAD, int value) {
|
||||
Node *new, *next = HEAD->next;
|
||||
HEAD->value = value;
|
||||
|
||||
while (next->value < value)
|
||||
next = next->next;
|
||||
if (next->value == value)
|
||||
return false;
|
||||
|
||||
new = malloc(sizeof(Node));
|
||||
new->value = value;
|
||||
new->next = next;
|
||||
new->prev = next->prev;
|
||||
new->prev->next = new->next->prev = new;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool removeFrom(Node *HEAD, int value) {
|
||||
Node * current = findIn(HEAD, value);
|
||||
|
||||
if (current == NULL)
|
||||
return false;
|
||||
current->next->prev = current->prev;
|
||||
current->prev->next = current->next;
|
||||
free(current);
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *prev, *next;
|
||||
} Node;
|
||||
|
||||
Node * initializeDequeue() {
|
||||
Node *HEAD = malloc(sizeof(*HEAD));
|
||||
HEAD->next = HEAD->prev = HEAD;
|
||||
return HEAD;
|
||||
}
|
||||
|
||||
int dequeueSize (Node *HEAD) {
|
||||
Node *n;
|
||||
int i = 0;
|
||||
|
||||
for (n = HEAD->next; n != HEAD; n = n->next)
|
||||
i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
void printDequeue(Node *HEAD) {
|
||||
Node *n;
|
||||
|
||||
printf("Deque: \" ");
|
||||
for (n = HEAD->next; n != HEAD; n = n->next)
|
||||
printf("%d,", n->value);
|
||||
printf("\"\n");
|
||||
}
|
||||
|
||||
void AppendDequeue (Node *HEAD, int value) {
|
||||
Node *n = malloc(sizeof(*n));
|
||||
n->value = value;
|
||||
n->next = HEAD;
|
||||
n->prev = HEAD->prev;
|
||||
HEAD->prev = n;
|
||||
n->prev->next = n;
|
||||
}
|
||||
|
||||
int popFirst (Node *HEAD) {
|
||||
Node *n = HEAD->next;
|
||||
int value = EOF;
|
||||
|
||||
if (n != HEAD) {
|
||||
value = n->value;
|
||||
HEAD->next = n->next;
|
||||
n->next->prev = HEAD;
|
||||
free(n);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
int popLast (Node *HEAD) {
|
||||
Node *n = HEAD->prev;
|
||||
int value = EOF;
|
||||
|
||||
if (n != HEAD) {
|
||||
value = n->value;
|
||||
HEAD->prev = n->prev;
|
||||
n->prev->next = HEAD;
|
||||
free(n);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
void reinitializeDequeue (Node *HEAD) {
|
||||
Node *next, *prev;
|
||||
|
||||
for (next = HEAD->next; next != HEAD; free(prev)) {
|
||||
prev = next;
|
||||
next = next->next;
|
||||
}
|
||||
HEAD->next = HEAD->prev = HEAD;
|
||||
}
|
||||
|
||||
void PrependDequeue (Node *HEAD, int value) {
|
||||
Node *n = malloc(sizeof(*n));
|
||||
n->value = value;
|
||||
n->prev = HEAD;
|
||||
n->next = HEAD->next;
|
||||
HEAD->next = n;
|
||||
n->next->prev = n;
|
||||
}
|
||||
|
||||
int greatestValue (Node *HEAD) {
|
||||
Node *n = HEAD->next;
|
||||
int value;
|
||||
|
||||
if (n == HEAD)
|
||||
return EOF;
|
||||
value = n->value;
|
||||
n = n->next;
|
||||
while (n != HEAD) {
|
||||
if (value < n->value)
|
||||
value = n->value;
|
||||
n = n->next;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
int main () {
|
||||
Node *HEAD = initializeDequeue();
|
||||
|
||||
/* code */
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct {
|
||||
int * value, size, top;
|
||||
} Stack;
|
||||
|
||||
Stack * initialize (int size) {
|
||||
Stack *s = malloc(sizeof(*s));
|
||||
s->value = malloc(size * sizeof(s->value));
|
||||
s->size = size;
|
||||
s->top = -1;
|
||||
return s;
|
||||
}
|
||||
|
||||
void printStack (Stack *s) {
|
||||
int i;
|
||||
|
||||
printf("Lista: \"");
|
||||
for (i = s->top; i >= 0; i--)
|
||||
printf("%d ", s->value[i]);
|
||||
printf("\"\n");
|
||||
}
|
||||
|
||||
void reversePrintStack (Stack *s) {
|
||||
int i;
|
||||
|
||||
printf("Pilha (da base para o topo): \" ");
|
||||
for (i = 0; i <= s->top; i++)
|
||||
printf("%d\n", s->value[i]);
|
||||
printf("\"\n");
|
||||
}
|
||||
|
||||
bool push (Stack * s, int value) {
|
||||
if (s->top >= s->size + 1)
|
||||
return false;
|
||||
s->top = s->top + 1;
|
||||
s->value[s->top] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
int pop (Stack * s) {
|
||||
if (s->top < 0)
|
||||
return EOF;
|
||||
s->top -= 1;
|
||||
return s->value[s->top + 1];
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *under;
|
||||
} Node;
|
||||
|
||||
int stackSize (Node *top) {
|
||||
Node *n;
|
||||
int i = 0;
|
||||
|
||||
for (n = top; n; n = n->under)
|
||||
i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
void printStack(Node *top) {
|
||||
Node *n;
|
||||
|
||||
printf("Pilha: \" ");
|
||||
for (n = top; n; n = n->under)
|
||||
printf("%d,", n->value);
|
||||
printf("\"\n");
|
||||
}
|
||||
|
||||
void push(Node *top, int value) {
|
||||
Node *n = malloc(sizeof(*n));
|
||||
|
||||
n->value = value;
|
||||
n->under = top;
|
||||
top = n;
|
||||
}
|
||||
|
||||
int pop (Node *top) {
|
||||
Node *n = top;
|
||||
int value;
|
||||
|
||||
if (!top)
|
||||
return EOF;
|
||||
value = top->value;
|
||||
top = top->under;
|
||||
free(n);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
void destroyStack (Node *top) {
|
||||
if (!top)
|
||||
return;
|
||||
destroyStack(top->under);
|
||||
free(top);
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *next;
|
||||
} Node;
|
||||
|
||||
typedef struct {
|
||||
Node *start, *end;
|
||||
} Queue;
|
||||
|
||||
int queueLength (Queue *q) {
|
||||
int i;
|
||||
Node *n = q->start;
|
||||
|
||||
for (i = 0; n; i++)
|
||||
n = n->next;
|
||||
return i;
|
||||
}
|
||||
|
||||
void printQueue (Queue *q) {
|
||||
Node *n;
|
||||
|
||||
printf("Fila: \" ");
|
||||
for (n = q->start; n; n = n->next)
|
||||
printf("%d ", n->value);
|
||||
printf("\"\n");
|
||||
}
|
||||
|
||||
void push (Queue *q, int value) {
|
||||
Node *n = malloc(sizeof(*n));
|
||||
|
||||
n->value = value;
|
||||
n->next = NULL;
|
||||
if (!q->start)
|
||||
q->start = n;
|
||||
else
|
||||
q->end->next = n;
|
||||
q->end = n;
|
||||
}
|
||||
|
||||
int pop (Queue *q) {
|
||||
int value;
|
||||
Node *n = q->start;
|
||||
|
||||
if (!n)
|
||||
return EOF;
|
||||
value = q->start->value;
|
||||
q->start = (n->next) ? n->next : NULL;
|
||||
if (!q->start)
|
||||
q->end = NULL;
|
||||
free(n);
|
||||
return value;
|
||||
}
|
||||
|
||||
void reinitializeQueue (Queue *q) {
|
||||
Node *n, *erase;
|
||||
|
||||
for (n = q->start; n; free(erase)) {
|
||||
erase = n;
|
||||
n = n->next;
|
||||
}
|
||||
q->start = q->end = NULL;
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *next;
|
||||
} Node;
|
||||
|
||||
typedef struct {
|
||||
Node *HEAD, *TAIL;
|
||||
} Queue;
|
||||
|
||||
void push (Queue *q, int value) {
|
||||
Node *n = malloc(sizeof(*n));
|
||||
|
||||
n->value = value;
|
||||
n->next = NULL;
|
||||
if (!q->HEAD->next)
|
||||
q->HEAD->next = n;
|
||||
else
|
||||
q->TAIL->next = n;
|
||||
q->TAIL = n;
|
||||
}
|
||||
|
||||
int pop (Queue *q) {
|
||||
int value;
|
||||
Node *n = q->HEAD->next;
|
||||
|
||||
if (!n)
|
||||
return EOF;
|
||||
value = n->value;
|
||||
q->HEAD->next = (n->next) ? n->next : NULL;
|
||||
if (!q->HEAD->next)
|
||||
q->TAIL = NULL;
|
||||
free(n);
|
||||
return value;
|
||||
}
|
||||
|
||||
void printQueue (Queue *q) {
|
||||
int i;
|
||||
Node *current = q->HEAD->next;
|
||||
|
||||
for (i = 0; current; i++) {
|
||||
printf("\nÍndice: %-6d Valor: %-6d (Endereços) Atual: %p Próximo: %p\n", i, current->value, current, current->next);
|
||||
current = current->next;
|
||||
}
|
||||
}
|
||||
|
||||
int main () {
|
||||
int i, value;
|
||||
char c;
|
||||
Queue q = {NULL};
|
||||
|
||||
q.HEAD = malloc(sizeof(q.HEAD));
|
||||
printf("Este programa adiciona valores inteiros à uma fila, e depois permite excluí-los da mesma.\nDigite uma sequência de valores e pressione ENTER: ");
|
||||
do {
|
||||
if(!scanf("%d%c", &i, &c)) {
|
||||
printf("Valor inválido detectado.");
|
||||
return 1;
|
||||
}
|
||||
push(&q, i);
|
||||
} while (c != '\n');
|
||||
printQueue(&q);
|
||||
|
||||
printf("\nDigite uma quantia de valores a serem apagados e pressione ENTER: ");
|
||||
i = 0;
|
||||
for (scanf("%d", &i); i > 0; i--) {
|
||||
value = pop(&q);
|
||||
if (value == EOF)
|
||||
break;
|
||||
printf("\nValor apagado: %d", value);
|
||||
}
|
||||
printf("\n");
|
||||
printQueue(&q);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct node {
|
||||
int value;
|
||||
struct node *next;
|
||||
} Node;
|
||||
|
||||
typedef struct {
|
||||
Node *start, *end;
|
||||
} Queue;
|
||||
|
||||
Node * newNode (int value) {
|
||||
Node *n = malloc(sizeof(Node));
|
||||
|
||||
n->value = value;
|
||||
n->next = NULL;
|
||||
return n;
|
||||
}
|
||||
|
||||
void push (Queue *q, int value) {
|
||||
Node *n = newNode(value);
|
||||
|
||||
if (q->start)
|
||||
q->end->next = n;
|
||||
else
|
||||
q->start = n;
|
||||
q->end = n;
|
||||
}
|
||||
|
||||
int pop (Queue *q) {
|
||||
int value;
|
||||
Node *n;
|
||||
|
||||
if (!q->start)
|
||||
return EOF;
|
||||
|
||||
n = q->start;
|
||||
value = n->value;
|
||||
q->start = n->next;
|
||||
if (q->end == n)
|
||||
q->end = NULL;
|
||||
free(n);
|
||||
return value;
|
||||
}
|
||||
|
||||
void printQueue (Queue *q) {
|
||||
int i;
|
||||
Node *n = q->start;
|
||||
|
||||
printf("\nInício (endereço): %p\n", q->start);
|
||||
for (i = 0; n; i++) {
|
||||
printf("Índice: %-6d Valor: %-6d (Endereços) Atual: %p Próximo: %p\n", i, n->value, n, n->next);
|
||||
n = n->next;
|
||||
}
|
||||
printf("Fim: (endereço): %p\n", q->end);
|
||||
}
|
||||
|
||||
int main () {
|
||||
int i, value;
|
||||
char c;
|
||||
Queue *q = calloc(1, sizeof(Queue));
|
||||
|
||||
printf("Este programa adiciona valores inteiros à uma fila, e depois permite excluí-los da mesma.\nDigite uma sequência de valores e pressione ENTER: ");
|
||||
do {
|
||||
if(!scanf("%d%c", &i, &c)) {
|
||||
printf("Valor inválido detectado.");
|
||||
return 1;
|
||||
}
|
||||
push(q, i);
|
||||
} while (c != '\n');
|
||||
printQueue(q);
|
||||
|
||||
printf("\nDigite uma quantia de valores a serem apagados e pressione ENTER: ");
|
||||
i = 0;
|
||||
for (scanf("%d", &i); i > 0; i--) {
|
||||
value = pop(q);
|
||||
if (value == EOF)
|
||||
break;
|
||||
printf("\nValor apagado: %d", value);
|
||||
}
|
||||
printf("\n");
|
||||
printQueue(q);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#define MAX 50
|
||||
|
||||
typedef struct {
|
||||
int a[50], top1, top2;
|
||||
} dStack;
|
||||
|
||||
dStack initializeStack () {
|
||||
dStack s;
|
||||
|
||||
s.top1 = -1;
|
||||
s.top2 = MAX;
|
||||
return s;
|
||||
}
|
||||
|
||||
int stackSize (dStack *s, int stack) {
|
||||
if (stack < 1 || stack > 2)
|
||||
return EOF;
|
||||
return (stack == 1) ? s->top1 + 1 : MAX - s->top2;
|
||||
}
|
||||
|
||||
bool printStack (dStack *s, int stack) {
|
||||
int i;
|
||||
|
||||
if (stack < 1 || stack > 2)
|
||||
return false;
|
||||
|
||||
printf("Pilha %d: \"", stack);
|
||||
|
||||
if (stack == 1)
|
||||
for (i = s->top1; i >= 0; i--)
|
||||
printf("%d ", s->a[i]);
|
||||
else
|
||||
for (i = s->top2; i < MAX; i++)
|
||||
printf("%d ", s->a[i]);
|
||||
|
||||
printf("\"\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool push (dStack *s, int stack, int value) {
|
||||
if (stack < 1 || stack > 2 || s->top1 + 1 == s->top2)
|
||||
return false;
|
||||
s->a[(stack == 1) ? ++s->top1 : --s->top2] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool pop (dStack *s, int stack, int *value) {
|
||||
if (stack < 1 || stack > 2)
|
||||
return false;
|
||||
if (stack == 1) {
|
||||
if (s->top1 < 0)
|
||||
return false;
|
||||
*value = s->a[s->top1--];
|
||||
}
|
||||
else {
|
||||
if (s->top2 >= MAX)
|
||||
return false;
|
||||
*value = s->a[s->top2++];
|
||||
}
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
i 1
|
||||
j 2
|
||||
k 3
|
||||
l
|
||||
n
|
||||
o
|
||||
p
|
||||
j 5
|
||||
j 4
|
||||
o
|
||||
j 6
|
||||
o
|
||||
j 7
|
||||
l
|
||||
d
|
||||
l
|
||||
i 1
|
||||
i 2
|
||||
i 3
|
||||
i 4
|
||||
i 5
|
||||
i 6
|
||||
i 7
|
||||
j 8
|
||||
k 9
|
||||
e
|
||||
f
|
||||
g
|
||||
j 10
|
||||
1
|
||||
2
|
||||
3
|
||||
e
|
||||
j 11
|
||||
n
|
||||
o
|
||||
p
|
||||
l
|
||||
f
|
||||
k 13
|
||||
n
|
||||
o
|
||||
p
|
||||
l
|
||||
g
|
||||
j 14
|
||||
n
|
||||
o
|
||||
p
|
||||
l
|
||||
q
|
|
@ -0,0 +1,86 @@
|
|||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#define MAX 8
|
||||
#define NS 4
|
||||
|
||||
typedef struct {
|
||||
int a[MAX], base[NS + 1], top[NS + 1];
|
||||
} mStack;
|
||||
|
||||
mStack initializeStack () {
|
||||
int i;
|
||||
mStack s;
|
||||
|
||||
for (i = 0; i < NS; i++) {
|
||||
s.base[i] = i * MAX / NS;
|
||||
s.top[i] = s.base[i] - 1;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
int stackSize (mStack *s, int stack) {
|
||||
if (stack < 0 || stack >= NS)
|
||||
return EOF;
|
||||
return s->top[stack] - s->base[stack] + 1;
|
||||
}
|
||||
|
||||
int stacksSize (mStack *s) {
|
||||
int i, size = 0;
|
||||
|
||||
for (i = 0; i < NS; i++)
|
||||
size += stackSize(s, i);
|
||||
return size;
|
||||
}
|
||||
|
||||
bool fullStack(mStack *s, int stack) {
|
||||
return (s->top[stack] == s->base[stack + 1] - 1) ? true : false;
|
||||
}
|
||||
|
||||
bool pop (mStack *s, int stack, int *value) {
|
||||
if (stack < 0 || stack >= NS || s->top[stack] < s->base[stack])
|
||||
return false;
|
||||
*value = s->a[s->top[stack]--];
|
||||
return true;
|
||||
}
|
||||
bool pushStack(mStack *s, int stack) {
|
||||
int i;
|
||||
|
||||
if (stack < 1 || stack >= NS || s->top[stack] == s->base[stack + 1] - 1)
|
||||
return false;
|
||||
for (i = s->top[stack]; i >= s->base[stack]; i--)
|
||||
s->a[i + 1] = s->a[i];
|
||||
s->top[stack]++;
|
||||
s->base[stack]++;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool pullStack(mStack *s, int stack) {
|
||||
int i;
|
||||
|
||||
if (stack < 1 || stack >= NS || s->base[stack] == s->top[stack - 1] + 1)
|
||||
return false;
|
||||
for (i = s->base[stack]; i >= s->top[stack]; i++)
|
||||
s->a[i - 1] = s->a[i];
|
||||
s->top[stack]--;
|
||||
s->base[stack]--;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool push (mStack *s, int stack, int value) {
|
||||
int i;
|
||||
|
||||
if (stack < 0 || stack >= NS)
|
||||
return false;
|
||||
if (fullStack(s, stack)) {
|
||||
for (i = NS - 1; i > stack; i--)
|
||||
pushStack(s, i);
|
||||
if (fullStack(s, stack))
|
||||
for (i = 1; i <= stack; i++)
|
||||
pullStack(s, i);
|
||||
if (fullStack(s, stack))
|
||||
return false;
|
||||
}
|
||||
s->top[stack]++;
|
||||
s->a[s->top[stack]] = value;
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
Comandos validos:
|
||||
i <chave1>: inserir elemento com chave=chave1, na pilha 1
|
||||
j <chave1>: inserir elemento com chave=chave1, na pilha 2
|
||||
k <chave1>: inserir elemento com chave=chave1, na pilha 3
|
||||
e : excluir elemento com chave=chave1, na pilha 1
|
||||
f : excluir elemento com chave=chave1, na pilha 2
|
||||
g : excluir elemento com chave=chave1, na pilha 3
|
||||
n : imprimir pilha 1
|
||||
o : imprimir pilha 2
|
||||
p : imprimir pilha 2
|
||||
d : destruir (zerar) pilhas
|
||||
l : exibir log de utilizacao do pilha
|
||||
h : exibir esta mensagem de ajuda
|
||||
1 : exibir a chave e o endereco do topo, pilha 1
|
||||
2 : exibir a chave e o endereco do topo, pilha 2
|
||||
3 : exibir a chave e o endereco do topo, pilha 3
|
||||
q : sair (quit)
|
||||
Elemento 1 inserido corretamente na pilha 1.
|
||||
Elemento 2 inserido corretamente na pilha 2.
|
||||
Elemento 3 inserido corretamente na pilha 3.
|
||||
Numero de elementos na pilha 1: 1.
|
||||
Numero de elementos na pilha 2: 1.
|
||||
Numero de elementos na pilha 3: 1.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Pilha 1: " 1 "
|
||||
Pilha 2: " 2 "
|
||||
Pilha 3: " 3 "
|
||||
Elemento 5 inserido corretamente na pilha 2.
|
||||
Elemento 4 inserido corretamente na pilha 2.
|
||||
Pilha 2: " 4 5 2 "
|
||||
Elemento 6 inserido corretamente na pilha 2.
|
||||
Pilha 2: " 6 4 5 2 "
|
||||
Nao foi possivel inserir elemento 7.
|
||||
Numero de elementos na pilha 1: 1.
|
||||
Numero de elementos na pilha 2: 4.
|
||||
Numero de elementos na pilha 3: 1.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Pilhas zeradas.
|
||||
Numero de elementos na pilha 1: 0.
|
||||
Numero de elementos na pilha 2: 0.
|
||||
Numero de elementos na pilha 3: 0.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Elemento 1 inserido corretamente na pilha 1.
|
||||
Elemento 2 inserido corretamente na pilha 1.
|
||||
Elemento 3 inserido corretamente na pilha 1.
|
||||
Elemento 4 inserido corretamente na pilha 1.
|
||||
Elemento 5 inserido corretamente na pilha 1.
|
||||
Elemento 6 inserido corretamente na pilha 1.
|
||||
Nao foi possivel inserir elemento 7.
|
||||
Nao foi possivel inserir elemento 8.
|
||||
Nao foi possivel inserir elemento 9.
|
||||
Elemento 6 excluido corretamente da pilha 1.
|
||||
Nao foi possivel excluir elemento pilha 2 - pilha vazio.
|
||||
Nao foi possivel excluir elemento pilha 3 - pilha vazio.
|
||||
Elemento 10 inserido corretamente na pilha 2.
|
||||
Primeiro elemento pilha 1: 5 encontrado no endereco 4.
|
||||
Primeiro elemento pilha 2: 10 encontrado no endereco 5.
|
||||
Nao foi possivel encontrar o primeiro elemento (pilha vazia).
|
||||
Elemento 5 excluido corretamente da pilha 1.
|
||||
Elemento 11 inserido corretamente na pilha 2.
|
||||
Pilha 1: " 4 3 2 1 "
|
||||
Pilha 2: " 11 10 "
|
||||
Pilha 3: " "
|
||||
Numero de elementos na pilha 1: 4.
|
||||
Numero de elementos na pilha 2: 2.
|
||||
Numero de elementos na pilha 3: 0.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Elemento 11 excluido corretamente da pilha 2.
|
||||
Elemento 13 inserido corretamente na pilha 3.
|
||||
Pilha 1: " 4 3 2 1 "
|
||||
Pilha 2: " 10 "
|
||||
Pilha 3: " 13 "
|
||||
Numero de elementos na pilha 1: 4.
|
||||
Numero de elementos na pilha 2: 1.
|
||||
Numero de elementos na pilha 3: 1.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Elemento 13 excluido corretamente da pilha 3.
|
||||
Elemento 14 inserido corretamente na pilha 2.
|
||||
Pilha 1: " 4 3 2 1 "
|
||||
Pilha 2: " 14 10 "
|
||||
Pilha 3: " "
|
||||
Numero de elementos na pilha 1: 4.
|
||||
Numero de elementos na pilha 2: 2.
|
||||
Numero de elementos na pilha 3: 0.
|
||||
Tamanho do pilha (em bytes): 40.
|
|
@ -0,0 +1,85 @@
|
|||
Comandos validos:
|
||||
i <chave1>: inserir elemento com chave=chave1, na pilha 1
|
||||
j <chave1>: inserir elemento com chave=chave1, na pilha 2
|
||||
k <chave1>: inserir elemento com chave=chave1, na pilha 3
|
||||
e : excluir elemento com chave=chave1, na pilha 1
|
||||
f : excluir elemento com chave=chave1, na pilha 2
|
||||
g : excluir elemento com chave=chave1, na pilha 3
|
||||
n : imprimir pilha 1
|
||||
o : imprimir pilha 2
|
||||
p : imprimir pilha 2
|
||||
d : destruir (zerar) pilhas
|
||||
l : exibir log de utilizacao do pilha
|
||||
h : exibir esta mensagem de ajuda
|
||||
1 : exibir a chave e o endereco do topo, pilha 1
|
||||
2 : exibir a chave e o endereco do topo, pilha 2
|
||||
3 : exibir a chave e o endereco do topo, pilha 3
|
||||
q : sair (quit)
|
||||
Elemento 1 inserido corretamente na pilha 1.
|
||||
Elemento 2 inserido corretamente na pilha 2.
|
||||
Elemento 3 inserido corretamente na pilha 3.
|
||||
Numero de elementos na pilha 1: 1.
|
||||
Numero de elementos na pilha 2: 1.
|
||||
Numero de elementos na pilha 3: 1.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Pilha 1: " 1 "
|
||||
Pilha 2: " 2 "
|
||||
Pilha 3: " 3 "
|
||||
Elemento 5 inserido corretamente na pilha 2.
|
||||
Elemento 4 inserido corretamente na pilha 2.
|
||||
Pilha 2: " 4 5 2 "
|
||||
Elemento 6 inserido corretamente na pilha 2.
|
||||
Pilha 2: " 6 4 5 2 "
|
||||
Nao foi possivel inserir elemento 7.
|
||||
Numero de elementos na pilha 1: 1.
|
||||
Numero de elementos na pilha 2: 4.
|
||||
Numero de elementos na pilha 3: 1.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Pilhas zeradas.
|
||||
Numero de elementos na pilha 1: 0.
|
||||
Numero de elementos na pilha 2: 0.
|
||||
Numero de elementos na pilha 3: 0.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Elemento 1 inserido corretamente na pilha 1.
|
||||
Elemento 2 inserido corretamente na pilha 1.
|
||||
Elemento 3 inserido corretamente na pilha 1.
|
||||
Elemento 4 inserido corretamente na pilha 1.
|
||||
Elemento 5 inserido corretamente na pilha 1.
|
||||
Elemento 6 inserido corretamente na pilha 1.
|
||||
Nao foi possivel inserir elemento 7.
|
||||
Nao foi possivel inserir elemento 8.
|
||||
Nao foi possivel inserir elemento 9.
|
||||
Elemento 6 excluido corretamente da pilha 1.
|
||||
Nao foi possivel excluir elemento pilha 2 - pilha vazio.
|
||||
Nao foi possivel excluir elemento pilha 3 - pilha vazio.
|
||||
Elemento 10 inserido corretamente na pilha 2.
|
||||
Primeiro elemento pilha 1: 5 encontrado no endereco 4.
|
||||
Primeiro elemento pilha 2: 10 encontrado no endereco 5.
|
||||
Nao foi possivel encontrar o primeiro elemento (pilha vazia).
|
||||
Elemento 5 excluido corretamente da pilha 1.
|
||||
Elemento 11 inserido corretamente na pilha 2.
|
||||
Pilha 1: " 4 3 2 1 "
|
||||
Pilha 2: " 11 10 "
|
||||
Pilha 3: " "
|
||||
Numero de elementos na pilha 1: 4.
|
||||
Numero de elementos na pilha 2: 2.
|
||||
Numero de elementos na pilha 3: 0.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Elemento 11 excluido corretamente da pilha 2.
|
||||
Elemento 13 inserido corretamente na pilha 3.
|
||||
Pilha 1: " 4 3 2 1 "
|
||||
Pilha 2: " 10 "
|
||||
Pilha 3: " 13 "
|
||||
Numero de elementos na pilha 1: 4.
|
||||
Numero de elementos na pilha 2: 1.
|
||||
Numero de elementos na pilha 3: 1.
|
||||
Tamanho do pilha (em bytes): 40.
|
||||
Elemento 13 excluido corretamente da pilha 3.
|
||||
Elemento 14 inserido corretamente na pilha 2.
|
||||
Pilha 1: " 4 3 2 1 "
|
||||
Pilha 2: " 14 10 "
|
||||
Pilha 3: " "
|
||||
Numero de elementos na pilha 1: 4.
|
||||
Numero de elementos na pilha 2: 2.
|
||||
Numero de elementos na pilha 3: 0.
|
||||
Tamanho do pilha (em bytes): 40.
|
|
@ -0,0 +1,166 @@
|
|||
/******************************************************************************
|
||||
// duasPilhasEstaticas.c
|
||||
// Este programa gerencia duas pilhas implementadas em um arranjo
|
||||
(implementacao estatica).
|
||||
// As pilhas gerenciadas podem ter um numero de no maximo MAX elementos (juntas).
|
||||
// N<>o usaremos sentinela nesta estrutura.
|
||||
******************************************************************************/
|
||||
#include <stdio.h>
|
||||
#define true 1
|
||||
#define false 0
|
||||
#define MAX 6
|
||||
|
||||
typedef int bool;
|
||||
typedef int TIPOCHAVE;
|
||||
|
||||
typedef struct {
|
||||
TIPOCHAVE chave;
|
||||
} REGISTRO;
|
||||
|
||||
typedef struct {
|
||||
REGISTRO A[MAX];
|
||||
int topo1;
|
||||
int base2;
|
||||
int topo2;
|
||||
int topo3;
|
||||
} PILHATRIPLA;
|
||||
|
||||
|
||||
/* Inicializa<7A><61>o da PILHATRIPLA (a PILHATRIPLA jah esta criada e eh apontada
|
||||
pelo endereco em p) */
|
||||
void inicializarPilhaTripla(PILHATRIPLA* p){
|
||||
p->topo1 = -1;
|
||||
p->base2 = MAX/3;
|
||||
p->topo2 = p->base2-1;
|
||||
p->topo3 = MAX;
|
||||
} /* inicializarPILHATRIPLA */
|
||||
|
||||
|
||||
/* Retornar o tamanho da PILHATRIPLA (numero de elementos das duas somadas) */
|
||||
int tamanhoPilhaTripla(PILHATRIPLA* p) {
|
||||
return p->topo1 + MAX - p->topo3 + p->topo2 - p->base2 + 2;
|
||||
} /* tamanhoPILHATRIPLA */
|
||||
|
||||
/* Retornar o tamanho de uma das pilhas */
|
||||
int tamanhoUmaPilha(PILHATRIPLA* p, int pilha) {
|
||||
if (pilha < 1 || pilha > 3) return -1;
|
||||
if (pilha == 1) return p->topo1+1;
|
||||
else if (pilha == 2) return p->topo2 - p->base2 + 1;
|
||||
return MAX-p->topo3;
|
||||
} /* tamanhoUmaPilha */
|
||||
|
||||
/* Exibi<62><69>o de uma das pilhas */
|
||||
void exibirUmaPilha(PILHATRIPLA* p, int pilha){
|
||||
if (pilha < 1 || pilha > 3) return;
|
||||
printf("Pilha %i: \" ", pilha);
|
||||
int i;
|
||||
if (pilha == 1) for (i=p->topo1;i>=0;i--) printf("%i ", p->A[i].chave);
|
||||
else if (pilha == 2) for (i=p->topo2;i>=p->base2;i--) printf("%i ", p->A[i].chave);
|
||||
else for (i=p->topo3;i<MAX;i++) printf("%i ", p->A[i].chave);
|
||||
printf("\"\n");
|
||||
} /* exibirPilha */
|
||||
|
||||
/* Retornar o tamanho em bytes da pilha. Neste caso, isto nao depende do numero
|
||||
de elementos que estao sendo usados. */
|
||||
int tamanhoEmBytesPilha(PILHATRIPLA* p) {
|
||||
return sizeof(PILHATRIPLA);
|
||||
} /* tamanhoEmBytes */
|
||||
|
||||
void reinicializarPilha(PILHATRIPLA* p) {
|
||||
p->topo1 = -1;
|
||||
p->base2 = MAX/3;
|
||||
p->topo2 = p->base2-1;
|
||||
p->topo3 = MAX;
|
||||
}
|
||||
|
||||
/* Destrui<75><69>o da pilha */
|
||||
void reinicializarPilha2(PILHATRIPLA* p) {
|
||||
inicializarPilhaTripla(p);
|
||||
} /* destruirPilha */
|
||||
|
||||
/* Desloca a pilha 2 uma posi<73><69>o <20> esquerda */
|
||||
bool deslocarAEsquerda(PILHATRIPLA* p){
|
||||
if (p->base2==p->topo1+1) return false;
|
||||
int x;
|
||||
for (x=p->base2; x<=p->topo2; x++) p->A[x-1] = p->A[x];
|
||||
p->base2--;
|
||||
p->topo2--;
|
||||
return true;
|
||||
} /* deslocarAEsquerda */
|
||||
|
||||
|
||||
/* Desloca a pilha 2 uma posi<73><69>o <20> direita */
|
||||
bool deslocarADireita(PILHATRIPLA* p){
|
||||
if (p->topo2==p->topo3-1) return false;
|
||||
int x;
|
||||
for (x=p->topo2; x>=p->base2; x--) p->A[x+1] = p->A[x];
|
||||
p->base2++;
|
||||
p->topo2++;
|
||||
return true;
|
||||
} /* deslocarAEsquerda */
|
||||
|
||||
/* inserirElementoPilha - insere elemento no fim da pilha */
|
||||
bool inserirElementoPilha(PILHATRIPLA* p, REGISTRO reg, int pilha){
|
||||
if (pilha < 1 || pilha > 3) return false;
|
||||
if (tamanhoPilhaTripla(p) == MAX) return false;
|
||||
if (pilha == 1) {
|
||||
if (p->topo1 == p->base2-1) deslocarADireita(p);
|
||||
p->topo1 = p->topo1+1;
|
||||
p->A[p->topo1] = reg;
|
||||
}else if(pilha==2){
|
||||
if (p->topo2 == p->topo3-1) deslocarAEsquerda(p);
|
||||
p->topo2++;
|
||||
p->A[p->topo2] = reg;
|
||||
}else{
|
||||
if (p->topo2 == p->topo3-1) deslocarAEsquerda(p);
|
||||
p->topo3 = p->topo3-1;
|
||||
p->A[p->topo3] = reg;
|
||||
}
|
||||
return true;
|
||||
} /* inserirElementoPilha */
|
||||
|
||||
|
||||
/* excluirElementoPilha - copia para o endere<72>o reg e exclui o registro do topo
|
||||
da pilha solicitada e retorna true;
|
||||
ou retorna false se nao houver elemento a ser retirado na respectiva pilha */
|
||||
bool excluirElementoPilha(PILHATRIPLA* p, REGISTRO* reg, int pilha){
|
||||
switch (pilha) {
|
||||
case 1:
|
||||
if (p->topo1 < 0)
|
||||
return false;
|
||||
*reg = p->A[p->topo1--];
|
||||
return true;
|
||||
case 2:
|
||||
if (p->topo2 < p->base2)
|
||||
return false;
|
||||
*reg = p->A[p->topo2--];
|
||||
return true;
|
||||
case 3:
|
||||
if (p->topo3 >= MAX)
|
||||
return false;
|
||||
*reg = p->A[p->topo3++];
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
} /* excluirElementoPilha */
|
||||
|
||||
/* retornarPrimeiroPilha
|
||||
retorna a posicao do primeiro (topo) elemento da pilha e o valor de sua chave no
|
||||
conteudo do endereco ch. Retorna -1 caso a lista esteja vazia */
|
||||
int retornarPrimeiroPilha(PILHATRIPLA* p, TIPOCHAVE* ch, int pilha){
|
||||
if (pilha < 1 || pilha > 3) return -1;
|
||||
if (pilha == 1){
|
||||
if (p->topo1==-1)return -1;
|
||||
*ch = p->A[p->topo1].chave;
|
||||
return p->topo1;
|
||||
}else if (pilha == 2){
|
||||
if (p->topo2<p->base2)return -1;
|
||||
*ch = p->A[p->topo2].chave;
|
||||
return p->topo2;
|
||||
}else{
|
||||
if (p->topo3==MAX)return -1;
|
||||
*ch = p->A[p->topo3].chave;
|
||||
return p->topo3;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,149 @@
|
|||
/******************************************************************************
|
||||
usaTresPilhasEstaticas.c
|
||||
Este programa interage com o usuario para o gerenciamento de tres pilhas
|
||||
alocadas num mesmo arranjo.
|
||||
******************************************************************************/
|
||||
#include "tresPilhasEstaticas.c"
|
||||
#include <stdio.h>
|
||||
|
||||
void inserir1(PILHATRIPLA* p){
|
||||
TIPOCHAVE ch;
|
||||
scanf("%i",&ch);
|
||||
REGISTRO reg;
|
||||
reg.chave = ch;
|
||||
if (inserirElementoPilha(p,reg,1)) printf("Elemento %i inserido corretamente na pilha 1.\n",ch);
|
||||
else printf("Nao foi possivel inserir elemento %i.\n",ch);
|
||||
}
|
||||
|
||||
void inserir2(PILHATRIPLA* p){
|
||||
TIPOCHAVE ch;
|
||||
scanf("%i",&ch);
|
||||
REGISTRO reg;
|
||||
reg.chave = ch;
|
||||
if (inserirElementoPilha(p,reg,2)) printf("Elemento %i inserido corretamente na pilha 2.\n",ch);
|
||||
else printf("Nao foi possivel inserir elemento %i.\n",ch);
|
||||
}
|
||||
|
||||
void inserir3(PILHATRIPLA* p){
|
||||
TIPOCHAVE ch;
|
||||
scanf("%i",&ch);
|
||||
REGISTRO reg;
|
||||
reg.chave = ch;
|
||||
if (inserirElementoPilha(p,reg,3)) printf("Elemento %i inserido corretamente na pilha 3.\n",ch);
|
||||
else printf("Nao foi possivel inserir elemento %i.\n",ch);
|
||||
}
|
||||
|
||||
void exibirPrimeiro1(PILHATRIPLA* p){
|
||||
TIPOCHAVE ch;
|
||||
int posicao = retornarPrimeiroPilha(p,&ch,1);
|
||||
if (posicao != -1) printf("Primeiro elemento pilha 1: %i encontrado no endereco %i.\n",ch,posicao);
|
||||
else printf("Nao foi possivel encontrar o primeiro elemento (pilha vazia).\n");
|
||||
}
|
||||
|
||||
void exibirPrimeiro2(PILHATRIPLA* p){
|
||||
TIPOCHAVE ch;
|
||||
int posicao = retornarPrimeiroPilha(p,&ch,2);
|
||||
if (posicao != -1) printf("Primeiro elemento pilha 2: %i encontrado no endereco %i.\n",ch,posicao);
|
||||
else printf("Nao foi possivel encontrar o primeiro elemento (pilha vazia).\n");
|
||||
}
|
||||
|
||||
void exibirPrimeiro3(PILHATRIPLA* p){
|
||||
TIPOCHAVE ch;
|
||||
int posicao = retornarPrimeiroPilha(p,&ch,3);
|
||||
if (posicao != -1) printf("Primeiro elemento pilha 3: %i encontrado no endereco %i.\n",ch,posicao);
|
||||
else printf("Nao foi possivel encontrar o primeiro elemento (pilha vazia).\n");
|
||||
}
|
||||
|
||||
void excluir1(PILHATRIPLA* p){
|
||||
REGISTRO reg;
|
||||
if (excluirElementoPilha(p,®,1)) printf("Elemento %i excluido corretamente da pilha 1.\n",reg.chave);
|
||||
else printf("Nao foi possivel excluir elemento pilha 1 - pilha vazio.\n");
|
||||
}
|
||||
|
||||
void excluir2(PILHATRIPLA* p){
|
||||
REGISTRO reg;
|
||||
if (excluirElementoPilha(p, ®,2)) printf("Elemento %i excluido corretamente da pilha 2.\n",reg.chave);
|
||||
else printf("Nao foi possivel excluir elemento pilha 2 - pilha vazio.\n");
|
||||
}
|
||||
|
||||
void excluir3(PILHATRIPLA* p){
|
||||
REGISTRO reg;
|
||||
if (excluirElementoPilha(p, ®,3)) printf("Elemento %i excluido corretamente da pilha 3.\n",reg.chave);
|
||||
else printf("Nao foi possivel excluir elemento pilha 3 - pilha vazio.\n");
|
||||
}
|
||||
|
||||
void exibir1(PILHATRIPLA* p){
|
||||
exibirUmaPilha(p,1);
|
||||
}
|
||||
|
||||
void exibir2(PILHATRIPLA* p){
|
||||
exibirUmaPilha(p,2);
|
||||
}
|
||||
|
||||
void exibir3(PILHATRIPLA* p){
|
||||
exibirUmaPilha(p,3);
|
||||
}
|
||||
|
||||
void meuLog(PILHATRIPLA* p){
|
||||
printf("Numero de elementos na pilha 1: %i.\n",tamanhoUmaPilha(p,1));
|
||||
printf("Numero de elementos na pilha 2: %i.\n",tamanhoUmaPilha(p,2));
|
||||
printf("Numero de elementos na pilha 3: %i.\n",tamanhoUmaPilha(p,3));
|
||||
printf("Tamanho do pilha (em bytes): %i.\n",tamanhoEmBytesPilha(p));
|
||||
}
|
||||
|
||||
void help(){
|
||||
printf("Comandos validos: \n");
|
||||
printf(" i <chave1>: inserir elemento com chave=chave1, na pilha 1\n");
|
||||
printf(" j <chave1>: inserir elemento com chave=chave1, na pilha 2\n");
|
||||
printf(" k <chave1>: inserir elemento com chave=chave1, na pilha 3\n");
|
||||
printf(" e : excluir elemento com chave=chave1, na pilha 1\n");
|
||||
printf(" f : excluir elemento com chave=chave1, na pilha 2\n");
|
||||
printf(" g : excluir elemento com chave=chave1, na pilha 3\n");
|
||||
printf(" n : imprimir pilha 1\n");
|
||||
printf(" o : imprimir pilha 2\n");
|
||||
printf(" p : imprimir pilha 2\n");
|
||||
printf(" d : destruir (zerar) pilhas\n");
|
||||
printf(" l : exibir log de utilizacao do pilha\n");
|
||||
printf(" h : exibir esta mensagem de ajuda\n");
|
||||
printf(" 1 : exibir a chave e o endereco do topo, pilha 1\n");
|
||||
printf(" 2 : exibir a chave e o endereco do topo, pilha 2\n");
|
||||
printf(" 3 : exibir a chave e o endereco do topo, pilha 3\n");
|
||||
printf(" q : sair (quit)\n");
|
||||
}
|
||||
|
||||
void destruir(PILHATRIPLA* p){
|
||||
reinicializarPilha(p);
|
||||
printf("Pilhas zeradas.\n");
|
||||
}
|
||||
|
||||
int main(){
|
||||
PILHATRIPLA pilha;
|
||||
inicializarPilhaTripla(&pilha);
|
||||
help();
|
||||
char comando = ' ';
|
||||
scanf("%c",&comando);
|
||||
while (comando != 'q'){
|
||||
switch (comando) {
|
||||
case 'i' : inserir1(&pilha); break;
|
||||
case 'j' : inserir2(&pilha); break;
|
||||
case 'k' : inserir3(&pilha); break;
|
||||
case 'e' : excluir1(&pilha); break;
|
||||
case 'f' : excluir2(&pilha); break;
|
||||
case 'g' : excluir3(&pilha); break;
|
||||
case 'n' : exibir1(&pilha); break;
|
||||
case 'o' : exibir2(&pilha); break;
|
||||
case 'p' : exibir3(&pilha); break;
|
||||
case 'd' : destruir(&pilha); break;
|
||||
case 'l' : meuLog(&pilha); break;
|
||||
case 'h' : help(); break;
|
||||
case '1' : exibirPrimeiro1(&pilha); break;
|
||||
case '2' : exibirPrimeiro2(&pilha); break;
|
||||
case '3' : exibirPrimeiro3(&pilha); break;
|
||||
|
||||
default: {while (comando != '\n') scanf("%c",&comando);};
|
||||
}
|
||||
scanf("%c",&comando);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
#include <stdio.h>
|
||||
#include <malloc.h>
|
||||
|
||||
typedef struct {
|
||||
int linhas;
|
||||
int colunas;
|
||||
int** M;
|
||||
}MATRIZ;
|
||||
|
||||
MATRIZ* inicializarMatriz(int linhas, int colunas){
|
||||
if (linhas<=0 || colunas<=0) return NULL;
|
||||
int i;
|
||||
MATRIZ* mat = (MATRIZ*) malloc(sizeof(MATRIZ));
|
||||
mat->M = (int**)malloc(sizeof(int*)*linhas);
|
||||
for (i=0; i<linhas; i++) {
|
||||
mat->M[i] = (int*)malloc(sizeof(int)*colunas);
|
||||
}
|
||||
mat->linhas = linhas;
|
||||
mat->colunas = colunas;
|
||||
return mat;
|
||||
}
|
||||
|
||||
void imprimirMatriz(MATRIZ* mat){
|
||||
int i,j;
|
||||
printf("Matriz %i x %i:\n", mat->linhas, mat->colunas);
|
||||
for (i=0; i<mat->linhas; i++) {
|
||||
for (j=0; j<mat->colunas; j++) printf("%i ", mat->M[i][j]);
|
||||
printf("\n");
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
MATRIZ *multiplicarMatrizes(MATRIZ *m1, MATRIZ *m2){
|
||||
int i,j,k;
|
||||
MATRIZ *res;
|
||||
|
||||
if (m1->colunas != m2->linhas)
|
||||
return NULL;
|
||||
res = inicializarMatriz(m1->linhas, m2->colunas);
|
||||
for (i = 0; i < res->linhas; i++) {
|
||||
for (j = 0; j < res->colunas; j++) {
|
||||
res->M[i][j] = 0;
|
||||
for (k = 0; k < m1->colunas; k++)
|
||||
res->M[i][j] += m1->M[i][k] * m2->M[k][j];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
int main(){
|
||||
|
||||
MATRIZ* m1 = inicializarMatriz(3, 2);
|
||||
int i,j;
|
||||
int cont = 1;
|
||||
for (i=0; i<m1->linhas; i++)
|
||||
for (j=0; j<m1->colunas; j++) {
|
||||
m1->M[i][j] = cont;
|
||||
cont++;
|
||||
}
|
||||
|
||||
imprimirMatriz(m1);
|
||||
|
||||
MATRIZ* m2 = inicializarMatriz(2, 3);
|
||||
for (i=0; i<m2->linhas; i++)
|
||||
for (j=0; j<m2->colunas; j++) {
|
||||
m2->M[i][j] = cont;
|
||||
cont++;
|
||||
}
|
||||
|
||||
imprimirMatriz(m2);
|
||||
|
||||
MATRIZ* m3 = multiplicarMatrizes(m1, m2);
|
||||
|
||||
imprimirMatriz(m3);
|
||||
|
||||
|
||||
char c1;
|
||||
printf("Pressione ENTER para terminar.\n");
|
||||
scanf("%c", &c1);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
Matriz 3 x 2:
|
||||
1 2
|
||||
3 4
|
||||
5 6
|
||||
|
||||
Matriz 2 x 3:
|
||||
7 8 9
|
||||
10 11 12
|
||||
|
||||
Matriz 3 x 3:
|
||||
27 30 33
|
||||
61 68 75
|
||||
95 106 117
|
||||
|
||||
Pressione ENTER para terminar.
|
|
@ -0,0 +1,103 @@
|
|||
#include <stdio.h>
|
||||
#include <malloc.h>
|
||||
#define true 1
|
||||
#define false 0
|
||||
typedef enum{esquerdo,direito} LADO;
|
||||
typedef int bool;
|
||||
typedef int TIPOCHAVE;
|
||||
|
||||
typedef struct aux{
|
||||
TIPOCHAVE chave;
|
||||
struct aux *esq, *dir;
|
||||
} NO, *PONT;
|
||||
|
||||
PONT buscarChave(TIPOCHAVE ch, PONT raiz){
|
||||
if (raiz == NULL) return NULL;
|
||||
if (raiz->chave == ch) return raiz;
|
||||
PONT aux = buscarChave(ch,raiz->esq);
|
||||
if (aux) return aux;
|
||||
return buscarChave(ch,raiz->dir);
|
||||
}
|
||||
|
||||
void apagar(PONT raiz){
|
||||
if (!raiz) return;
|
||||
apagar(raiz->esq);
|
||||
apagar(raiz->dir);
|
||||
free(raiz);
|
||||
}
|
||||
|
||||
PONT criarNovoNo(TIPOCHAVE ch){
|
||||
PONT novoNo = (PONT)malloc(sizeof(NO));
|
||||
novoNo->esq = novoNo->dir = NULL;
|
||||
novoNo->chave = ch;
|
||||
return novoNo;
|
||||
}
|
||||
|
||||
bool inserirFilho(PONT raiz, TIPOCHAVE novaChave, TIPOCHAVE chavePai, LADO lado){
|
||||
PONT pai = buscarChave(chavePai,raiz);
|
||||
if (!pai) return false;
|
||||
PONT novo = criarNovoNo(novaChave);
|
||||
if (lado == esquerdo){
|
||||
apagar(pai->esq);
|
||||
pai->esq = novo;
|
||||
}else{
|
||||
apagar(pai->dir);
|
||||
pai->dir = novo;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void exibirArvoreOrdemW(PONT raiz){
|
||||
if (raiz == NULL) return;
|
||||
exibirArvoreOrdemW(raiz->esq);
|
||||
exibirArvoreOrdemW(raiz->dir);
|
||||
printf("%i ",raiz->chave);
|
||||
}
|
||||
|
||||
int max(int a, int b){
|
||||
if (a>b) return a;
|
||||
return b;
|
||||
}
|
||||
|
||||
int funcaoZZZ(PONT raiz){
|
||||
if (!raiz ) return -1;
|
||||
return 1 + max(funcaoZZZ(raiz->esq), funcaoZZZ(raiz->dir));
|
||||
}
|
||||
|
||||
int funcaoX(PONT raiz){
|
||||
if (!raiz ) return 0;
|
||||
return 1 + funcaoX(raiz->esq) + funcaoX(raiz->dir);
|
||||
}
|
||||
|
||||
void inicializar(PONT* raiz){
|
||||
*raiz = NULL;
|
||||
}
|
||||
|
||||
void criarRaiz(PONT* raiz, TIPOCHAVE novaChave){
|
||||
*raiz = criarNovoNo(novaChave);
|
||||
}
|
||||
|
||||
|
||||
int main(){
|
||||
PONT raiz;
|
||||
inicializar(&raiz);
|
||||
criarRaiz(&raiz,1);
|
||||
inserirFilho(raiz,2,1,direito);
|
||||
inserirFilho(raiz,3,1,esquerdo);
|
||||
printf("FuncaoZZZ (1a execucao): %i\n",funcaoZZZ(raiz));
|
||||
printf("FuncaoX (1a execucao): %i\n",funcaoX(raiz));
|
||||
printf("Imprimindo (1a execucao): ");
|
||||
exibirArvoreOrdemW(raiz);
|
||||
printf("\n");
|
||||
|
||||
inserirFilho(raiz,4,2,esquerdo);
|
||||
inserirFilho(raiz,5,2,direito);
|
||||
inserirFilho(raiz,6,2,esquerdo);
|
||||
inserirFilho(raiz,7,6,direito);
|
||||
printf("FuncaoZZZ (2a execucao): %i\n",funcaoZZZ(raiz));
|
||||
printf("FuncaoX (2a execucao): %i\n",funcaoX(raiz));
|
||||
printf("Imprimindo (2a execucao): ");
|
||||
exibirArvoreOrdemW(raiz);
|
||||
printf("\n");
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef enum {left, right} side;
|
||||
|
||||
typedef struct node{
|
||||
int value;
|
||||
struct node *left, *right;
|
||||
} Node;
|
||||
|
||||
Node * findValue (Node *parent, int value) {
|
||||
Node * n;
|
||||
|
||||
if (!parent || parent->value == value)
|
||||
return parent;
|
||||
n = findValue(parent->left, value);
|
||||
return (n) ? n : findValue(parent->right, value);
|
||||
}
|
||||
|
||||
Node * newNode (int value) {
|
||||
Node *new = malloc(sizeof(Node));
|
||||
|
||||
new->value = value;
|
||||
new->left = new->right = NULL;
|
||||
return new;
|
||||
}
|
||||
|
||||
void createRoot (Node **root, int value) {
|
||||
*root = newNode(value);
|
||||
}
|
||||
|
||||
bool setChild (Node *root, int childValue, int parentValue, side s) {
|
||||
Node *child, *parent = findValue(root, parentValue);
|
||||
|
||||
if (!parent)
|
||||
return false;
|
||||
|
||||
child = newNode(childValue);
|
||||
if (s == left) {
|
||||
child->left = parent->left;
|
||||
parent->left = child;
|
||||
}
|
||||
else {
|
||||
child->right = parent->right;
|
||||
parent->right = child;
|
||||
}
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct node{
|
||||
int value;
|
||||
|
||||
/* Pointers to nodes which store values that are less or equal (le) and
|
||||
greater than (gt) the current node's. */
|
||||
struct node *parent, *le, *gt;
|
||||
} Node;
|
||||
|
||||
Node * newNode(int value){
|
||||
Node *new = malloc(sizeof(Node));
|
||||
new->parent = new->le = new->gt = NULL;
|
||||
new->value = value;
|
||||
return new;
|
||||
}
|
||||
|
||||
void insertNode(Node **root, Node *new) {
|
||||
if (!*root) {
|
||||
*root = new;
|
||||
return;
|
||||
}
|
||||
new->parent = *root;
|
||||
if (new->value > (*root)->value)
|
||||
insertNode(&(*root)->gt, new);
|
||||
else
|
||||
insertNode(&(*root)->le, new);
|
||||
}
|
||||
|
||||
Node * findNode(Node *root, int value) {
|
||||
if (!root)
|
||||
return NULL;
|
||||
if (root->value == value)
|
||||
return root;
|
||||
if (root->value > value)
|
||||
return findNode(root->le, value);
|
||||
return findNode(root->gt, value);
|
||||
}
|
||||
|
||||
Node * findMaxValue (Node *root) {
|
||||
if (!root->gt)
|
||||
return root;
|
||||
return findMaxValue(root->gt);
|
||||
}
|
||||
|
||||
void rearrangeTree (Node *root, Node *branch) {
|
||||
if (branch->parent != root) {
|
||||
branch->parent->gt = branch->le;
|
||||
branch->le = root->le;
|
||||
}
|
||||
branch->gt = root->gt;
|
||||
}
|
||||
|
||||
Node * selectBranch (Node *root) {
|
||||
Node *branch;
|
||||
|
||||
if (root->le) {
|
||||
if (!root->gt)
|
||||
return root->le;
|
||||
branch = findMaxValue(root->le);
|
||||
rearrangeTree(root, branch);
|
||||
return branch;
|
||||
}
|
||||
return root->gt;
|
||||
}
|
||||
|
||||
void substituteNode (Node *root, Node *branch) {
|
||||
if (branch) {
|
||||
if (root->parent) {
|
||||
if (root->value < root->parent->value)
|
||||
root->parent->le = branch;
|
||||
else
|
||||
root->parent->gt = branch;
|
||||
branch->parent = root->parent;
|
||||
}
|
||||
else
|
||||
branch->parent = NULL;
|
||||
}
|
||||
free(root);
|
||||
root = branch;
|
||||
}
|
||||
|
||||
bool excludeNode(Node **root, int value) {
|
||||
if (!*root)
|
||||
return false;
|
||||
if ((*root)->value != value)
|
||||
return excludeNode((value > (*root)->value) ? &(*root)->gt : &(*root)->le, value);
|
||||
substituteNode(*root, selectBranch(*root));
|
||||
return true;
|
||||
}
|
||||
|
||||
int treeSize (Node *root) {
|
||||
if (!root)
|
||||
return 0;
|
||||
return treeSize(root->le) + treeSize(root->gt) + 1;
|
||||
}
|
||||
|
||||
int main () {
|
||||
Node *new = newNode(23), *r = NULL;
|
||||
insertNode(&r,new);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct node{
|
||||
int value;
|
||||
struct node *lt, *gt;
|
||||
} Node;
|
||||
|
||||
Node * newNode(int value){
|
||||
Node *new = malloc(sizeof(Node));
|
||||
|
||||
new->lt = new->gt = NULL;
|
||||
new->value = value;
|
||||
return new;
|
||||
}
|
||||
|
||||
/* Node insertion */
|
||||
|
||||
bool insertNode(Node **root, int value) {
|
||||
if (!*root) {
|
||||
*root = newNode(value);
|
||||
return true;
|
||||
}
|
||||
if (value == (*root)->value)
|
||||
return false;
|
||||
if (value > (*root)->value)
|
||||
return insertNode(&(*root)->gt, value);
|
||||
return insertNode(&(*root)->lt, value);
|
||||
}
|
||||
|
||||
Node * findNode(Node *root, int value) {
|
||||
if (!root)
|
||||
return NULL;
|
||||
if (root->value == value)
|
||||
return root;
|
||||
if (value > root->value)
|
||||
return findNode(root->gt, value);
|
||||
return findNode(root->lt, value);
|
||||
}
|
||||
|
||||
/* Node removal */
|
||||
|
||||
Node * findMaxValue (Node *root, Node **parent) {
|
||||
if (!root->gt)
|
||||
return root;
|
||||
*parent = root;
|
||||
return findMaxValue(root->gt, parent);
|
||||
}
|
||||
|
||||
void rearrangePointers (Node *root, Node *parent, Node *child) {
|
||||
child->gt = root->gt;
|
||||
if (root == parent)
|
||||
return;
|
||||
parent->gt = child->lt;
|
||||
child->lt = root->lt;
|
||||
}
|
||||
|
||||
Node * selectByValue (Node *root) {
|
||||
Node *parent = root, *child = findMaxValue(root->lt, &parent);
|
||||
|
||||
rearrangePointers (root, parent, child);
|
||||
return child;
|
||||
}
|
||||
|
||||
Node * selectChild (Node *root) {
|
||||
if (root->lt) {
|
||||
if (!root->gt)
|
||||
return root->lt;
|
||||
return selectByValue(root);
|
||||
}
|
||||
return root->gt;
|
||||
}
|
||||
|
||||
void substituteRoot (Node **root, Node *newRoot) {
|
||||
free(*root);
|
||||
*root = newRoot;
|
||||
}
|
||||
|
||||
void substituteChild (Node *parent, Node *child, Node *newChild) {
|
||||
if (child == parent->lt)
|
||||
parent->lt = newChild;
|
||||
else
|
||||
parent->gt = newChild;
|
||||
free(child);
|
||||
}
|
||||
|
||||
bool excludeChild (Node **parent, int value) {
|
||||
Node **child = (value < (*parent)->value) ? &(*parent)->lt : &(*parent)->gt;
|
||||
|
||||
if (!*child)
|
||||
return false;
|
||||
if ((*child)->value == value) {
|
||||
substituteChild(*parent, *child, selectChild(*child));
|
||||
return true;
|
||||
}
|
||||
excludeChild(child, value);
|
||||
}
|
||||
|
||||
bool excludeNode(Node **root, int value) {
|
||||
if (!*root)
|
||||
return false;
|
||||
if (value == (*root)->value) {
|
||||
substituteRoot(root, selectChild(*root));
|
||||
return true;
|
||||
}
|
||||
return excludeChild(root, value);
|
||||
}
|
||||
|
||||
/* Printing output */
|
||||
|
||||
int treeSize (Node *root) {
|
||||
if (!root)
|
||||
return 0;
|
||||
return treeSize(root->lt) + treeSize(root->gt) + 1;
|
||||
}
|
||||
|
||||
int main () {
|
||||
Node *r = NULL;
|
||||
insertNode(&r,23);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct branch{
|
||||
int value;
|
||||
struct branch *parent, *le, *gt;
|
||||
} Branch;
|
||||
|
||||
typedef struct node {
|
||||
Branch *b;
|
||||
struct node *next, *prev;
|
||||
} Node;
|
||||
|
||||
Branch * newBranch(int value){
|
||||
Branch *new = malloc(sizeof(Branch));
|
||||
new->parent = new->le = new->gt = NULL;
|
||||
new->value = value;
|
||||
return new;
|
||||
}
|
||||
|
||||
/* Functions for printing a sorted sequence */
|
||||
|
||||
void insertBranch(Branch **root, Branch *new) {
|
||||
if (!*root) {
|
||||
*root = new;
|
||||
return;
|
||||
}
|
||||
new->parent = *root;
|
||||
if (new->value > (*root)->value)
|
||||
insertBranch(&(*root)->gt, new);
|
||||
else
|
||||
insertBranch(&(*root)->le, new);
|
||||
}
|
||||
|
||||
void printValues (Branch *root) {
|
||||
if (!root)
|
||||
return;
|
||||
printValues(root->le);
|
||||
printf("%d ", root->value);
|
||||
printValues(root->gt);
|
||||
}
|
||||
|
||||
void printSortedList (Branch *root) {
|
||||
printValues(root);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
/* Functions to print the tree level by level */
|
||||
|
||||
Node * initializeNode() {
|
||||
Node *n = malloc(sizeof(Node));
|
||||
n->b = NULL;
|
||||
n->prev = n->next = n;
|
||||
return n;
|
||||
}
|
||||
|
||||
void addBranch (Node *HEAD, Branch *b) {
|
||||
Node *new = initializeNode();
|
||||
|
||||
new->b = b;
|
||||
new->next = HEAD;
|
||||
if (HEAD->prev == HEAD) {
|
||||
HEAD->next = new;
|
||||
new->prev = HEAD;
|
||||
}
|
||||
else {
|
||||
HEAD->prev->next = new;
|
||||
new->prev = HEAD->prev;
|
||||
}
|
||||
HEAD->prev = new;
|
||||
}
|
||||
|
||||
Branch * removeFirst(Node *HEAD) {
|
||||
Node *next = HEAD->next;
|
||||
Branch *b = next->b;
|
||||
|
||||
HEAD->next = next->next;
|
||||
HEAD->next->prev = HEAD;
|
||||
free(next);
|
||||
return b;
|
||||
}
|
||||
|
||||
void printTree (Branch *root) {
|
||||
Node *queue;
|
||||
Branch *b;
|
||||
|
||||
if (!root)
|
||||
return;
|
||||
queue = initializeNode();
|
||||
addBranch(queue, root);
|
||||
while (queue != queue->next) {
|
||||
b = removeFirst(queue);
|
||||
printf("%d ", b->value);
|
||||
if (b->le)
|
||||
addBranch(queue, b->le);
|
||||
if (b->gt)
|
||||
addBranch(queue, b->gt);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main () {
|
||||
int i;
|
||||
char c;
|
||||
Branch *root = NULL;
|
||||
|
||||
printf("This program reads integer values and stores them in a binary tree memory structure. Then, these values are printed in an sorted sequence and as they were placed in the tree, respectively.\nType in any sequence of integers and then press ENTER:\n");
|
||||
do {
|
||||
if (scanf(" %d", &i))
|
||||
insertBranch(&root, newBranch(i));
|
||||
} while ((c = getchar()) != EOF && c != '\n');
|
||||
|
||||
printf("\nSorted sequence:\n");
|
||||
printSortedList(root);
|
||||
printf("\nTree:\n");
|
||||
printTree(root);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,178 @@
|
|||
/******************************************************************************
|
||||
arvoreEnaria2.c
|
||||
Este programa gerencia arvores n-arias (cada noh pode ter um numero ilimitado
|
||||
de filhos). Cada noh possui dois ponteiros um para seu ultimo filho e um para
|
||||
o seu irmao a direita (essa lista de irmaos funciona como uma lista ligada).
|
||||
******************************************************************************/
|
||||
#include <malloc.h>
|
||||
#include <stdio.h>
|
||||
#define true 1
|
||||
#define false 0
|
||||
|
||||
typedef int bool;
|
||||
typedef char TIPOCHAVE;
|
||||
|
||||
typedef struct auxNo {
|
||||
TIPOCHAVE chave;
|
||||
struct auxNo * ultimoFilho;
|
||||
struct auxNo * proximoIrmao;
|
||||
} NO, *PONT;
|
||||
|
||||
|
||||
/* retorna o endereco do NO que contem chave=ch ou NULL caso a chave nao seja
|
||||
encontrada. */
|
||||
PONT buscarChave(PONT raiz, TIPOCHAVE ch){
|
||||
if (raiz == NULL) return NULL;
|
||||
if (raiz->chave == ch) return raiz;
|
||||
PONT aux = buscarChave(raiz->ultimoFilho, ch);
|
||||
if (aux) return aux;
|
||||
return buscarChave(raiz->proximoIrmao, ch);
|
||||
}
|
||||
|
||||
/* retorna o tamanho (numero de nos da arvore) */
|
||||
int numeroDeNos(PONT raiz){
|
||||
if (!raiz) return 0;
|
||||
int res = 1;
|
||||
PONT filhos = raiz->ultimoFilho;
|
||||
while (filhos != NULL) {
|
||||
res += numeroDeNos(filhos);
|
||||
filhos = filhos->proximoIrmao;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* retorna o tamanho (numero de nos da arvore) */
|
||||
int numeroDeNos2(PONT raiz){
|
||||
if (!raiz) return 0;
|
||||
return 1 + numeroDeNos2(raiz->ultimoFilho) + numeroDeNos2(raiz->proximoIrmao);
|
||||
}
|
||||
|
||||
/* retorna a altura da arvore */
|
||||
int altura(PONT raiz){
|
||||
if (!raiz) return -1;
|
||||
int max = -1;
|
||||
int temp;
|
||||
PONT filhos = raiz->ultimoFilho;
|
||||
while (filhos != NULL) {
|
||||
temp = altura(filhos);
|
||||
if (temp > max) max = temp;
|
||||
filhos = filhos->proximoIrmao;
|
||||
}
|
||||
return max + 1;
|
||||
}
|
||||
PONT criarNovoNo(TIPOCHAVE ch){
|
||||
PONT novoNo = (PONT)malloc(sizeof(NO));
|
||||
novoNo->ultimoFilho = NULL;
|
||||
novoNo->proximoIrmao = NULL;
|
||||
novoNo->chave = ch;
|
||||
return novoNo;
|
||||
}
|
||||
|
||||
bool inserirFilho(PONT raiz, TIPOCHAVE novaChave, TIPOCHAVE chavePai){
|
||||
PONT pai = buscarChave(raiz, chavePai);
|
||||
if (!pai) return false;
|
||||
PONT novo = criarNovoNo(novaChave);
|
||||
novo->ultimoFilho = NULL;
|
||||
novo->proximoIrmao = pai->ultimoFilho;
|
||||
pai->ultimoFilho = novo;
|
||||
return true;
|
||||
}
|
||||
|
||||
void exibirArvore(PONT raiz){
|
||||
if (raiz == NULL) return;
|
||||
printf("%c",raiz->chave);
|
||||
PONT filhos = raiz->ultimoFilho;
|
||||
if (filhos == NULL) return;
|
||||
printf("(");
|
||||
while (filhos != NULL) {
|
||||
exibirArvore(filhos);
|
||||
filhos = filhos->proximoIrmao;
|
||||
}
|
||||
printf(")");
|
||||
}
|
||||
|
||||
PONT criarRaiz(TIPOCHAVE novaChave){
|
||||
return criarNovoNo(novaChave);
|
||||
}
|
||||
|
||||
void encontrarMinMaxRec(PONT raiz, char* min, char* max){
|
||||
if (!raiz)
|
||||
return;
|
||||
if (raiz->chave < *min)
|
||||
*min = raiz->chave;
|
||||
else if (raiz->chave > *max)
|
||||
*max = raiz->chave;
|
||||
encontrarMinMaxRec(raiz->ultimoFilho, min, max);
|
||||
encontrarMinMaxRec(raiz->proximoIrmao, min, max);
|
||||
}
|
||||
|
||||
bool encontrarMinMax(PONT raiz, char* min, char* max){
|
||||
if (!raiz) return false;
|
||||
*min = raiz->chave;
|
||||
*max = raiz->chave;
|
||||
encontrarMinMaxRec(raiz, min, max);
|
||||
return true;
|
||||
}
|
||||
|
||||
int main(){
|
||||
PONT raiz = criarRaiz('a');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'b','a');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'c','a');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'d','a');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'e','b');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'f','b');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'g','b');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'h','d');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'i','h');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
inserirFilho(raiz,'j','h');
|
||||
printf("Numero de nos: %i\n", numeroDeNos(raiz));
|
||||
printf("Altura: %i\n", altura(raiz));
|
||||
exibirArvore(raiz);
|
||||
printf("\n");
|
||||
char min1, max1;
|
||||
if (encontrarMinMax(raiz, &min1, &max1)) {
|
||||
printf("Menor chave na arvore: %c, maior chave na arvore: %c\n", min1, max1);
|
||||
}
|
||||
|
||||
char fim;
|
||||
printf("\nPressione <ENTER> para terminar.\n");
|
||||
scanf("%c",&fim);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct node{
|
||||
int value;
|
||||
struct node *parent, *le, *gt;
|
||||
} Node;
|
||||
|
||||
Node * newNode(int value){
|
||||
Node *new = malloc(sizeof(Node));
|
||||
new->parent = new->le = new->gt = NULL;
|
||||
new->value = value;
|
||||
return new;
|
||||
}
|
||||
|
||||
void insertNode(Node **root, Node *new) {
|
||||
if (!*root) {
|
||||
*root = new;
|
||||
return;
|
||||
}
|
||||
new->parent = *root;
|
||||
if (new->value > (*root)->value)
|
||||
insertNode(&(*root)->gt, new);
|
||||
else
|
||||
insertNode(&(*root)->le, new);
|
||||
}
|
||||
|
||||
Node * findNode(Node *root, int value) {
|
||||
if (!root)
|
||||
return NULL;
|
||||
if (root->value == value)
|
||||
return root;
|
||||
if (root->value > value)
|
||||
return findNode(root->le, value);
|
||||
return findNode(root->gt, value);
|
||||
}
|
||||
|
||||
Node * findMaxValue (Node *root) {
|
||||
if (!root->gt)
|
||||
return root;
|
||||
return findMaxValue(root->gt);
|
||||
}
|
||||
|
||||
void rearrangeTree (Node *root, Node *branch) {
|
||||
if (branch->parent != root) {
|
||||
branch->parent->gt = branch->le;
|
||||
branch->le = root->le;
|
||||
}
|
||||
branch->gt = root->gt;
|
||||
}
|
||||
|
||||
Node * selectBranch (Node *root) {
|
||||
Node *branch;
|
||||
|
||||
if (root->le) {
|
||||
if (!root->gt)
|
||||
return root->le;
|
||||
branch = findMaxValue(root->le);
|
||||
rearrangeTree(root, branch);
|
||||
return branch;
|
||||
}
|
||||
return root->gt;
|
||||
}
|
||||
|
||||
void substituteNode (Node *root, Node *branch) {
|
||||
if (branch) {
|
||||
if (root->parent) {
|
||||
if (root->value < root->parent->value)
|
||||
root->parent->le = branch;
|
||||
else
|
||||
root->parent->gt = branch;
|
||||
branch->parent = root->parent;
|
||||
}
|
||||
else
|
||||
branch->parent = NULL;
|
||||
}
|
||||
free(root);
|
||||
root = branch;
|
||||
}
|
||||
|
||||
bool excludeNode(Node **root, int value) {
|
||||
if (!*root)
|
||||
return false;
|
||||
if ((*root)->value != value)
|
||||
return excludeNode((value > (*root)->value) ? &(*root)->gt : &(*root)->le, value);
|
||||
substituteNode(*root, selectBranch(*root));
|
||||
return true;
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct node{
|
||||
int value;
|
||||
struct node *child, *parent, *sibling;
|
||||
} Node;
|
||||
|
||||
Node * findNode (Node *root, int value);
|
||||
Node * searchChild (Node *child, int value);
|
||||
|
||||
Node * newNode (int value) {
|
||||
Node *new = malloc(sizeof(Node));
|
||||
new->value = value;
|
||||
new->child->parent->sibling = NULL;
|
||||
return new;
|
||||
}
|
||||
|
||||
void addSibling (Node * child, Node *n) {
|
||||
if (!child->sibling)
|
||||
child->sibling = n;
|
||||
else
|
||||
addSibling(child->sibling, n);
|
||||
}
|
||||
|
||||
bool insertNode (Node *root, Node *n, int target) {
|
||||
root = findNode(root, target);
|
||||
if (!root)
|
||||
return false;
|
||||
if (!root->child)
|
||||
root->child = n;
|
||||
else
|
||||
addSibling(root->child, n);
|
||||
return true;
|
||||
}
|
||||
|
||||
Node * searchChild(Node *child, int value) {
|
||||
Node *target;
|
||||
|
||||
if(!child)
|
||||
return NULL;
|
||||
target = findNode(child, value);
|
||||
if (target)
|
||||
return target;
|
||||
return searchChild(child->sibling, value);
|
||||
}
|
||||
|
||||
Node * findNode(Node *root, int value) {
|
||||
if (!root)
|
||||
return NULL;
|
||||
if (root->value == value)
|
||||
return root;
|
||||
return searchChild(root->child, value);
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
#include "./AVL_tree.h"
|
||||
|
||||
/* Driver program to test above function*/
|
||||
int main() {
|
||||
Node *root = NULL;
|
||||
|
||||
insertNode(&root, 9);
|
||||
insertNode(&root, 5);
|
||||
insertNode(&root, 10);
|
||||
insertNode(&root, 0);
|
||||
insertNode(&root, 6);
|
||||
insertNode(&root, 11);
|
||||
insertNode(&root, -1);
|
||||
insertNode(&root, 1);
|
||||
insertNode(&root, 2);
|
||||
|
||||
/* The constructed AVL Tree would be
|
||||
9
|
||||
/ \
|
||||
1 10
|
||||
/ \ \
|
||||
0 5 11
|
||||
/ / \
|
||||
-1 2 6
|
||||
*/
|
||||
|
||||
printf("Preorder traversal of the constructed AVL tree is \n");
|
||||
preOrder(root);
|
||||
printf("\n");
|
||||
|
||||
printf("Sixth smallest value is: %d\n", getValue(root, 5));
|
||||
|
||||
removeNode(&root, 10);
|
||||
|
||||
/* The AVL Tree after deletion of 10
|
||||
1
|
||||
/ \
|
||||
0 9
|
||||
/ / \
|
||||
-1 5 11
|
||||
/ \
|
||||
2 6
|
||||
*/
|
||||
|
||||
printf("Preorder traversal of the constructed AVL tree is \n");
|
||||
preOrder(root);
|
||||
printf("\n");
|
||||
|
||||
printf("Now let's delete everything one by one.\n");
|
||||
|
||||
destroyTree(&root);
|
||||
|
||||
printf("Preorder traversal of the constructed AVL tree is \n");
|
||||
preOrder(root);
|
||||
printf("\n");
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,204 @@
|
|||
#ifndef FUNCTIONFILE_C
|
||||
#define FUNCTIONFILE_C
|
||||
#include "./AVL_tree.h"
|
||||
|
||||
/* Node insertion */
|
||||
|
||||
bool insertNode(Node **root, int value) {
|
||||
Node **n;
|
||||
|
||||
if (!*root) {
|
||||
*root = newNode(value);
|
||||
return true;
|
||||
}
|
||||
if (value == (*root)->value)
|
||||
return false;
|
||||
n = (value < (*root)->value) ? &(*root)->lt : &(*root)->gt;
|
||||
if (!insertNode(n, value))
|
||||
return false;
|
||||
*root = balanceTree(*root);
|
||||
return true;
|
||||
}
|
||||
|
||||
Node *newNode(int value) {
|
||||
Node *new = malloc(sizeof(Node));
|
||||
|
||||
new->value = value;
|
||||
new->height = 0;
|
||||
new->lt = new->gt = NULL;
|
||||
return new;
|
||||
}
|
||||
|
||||
/* Node removal */
|
||||
|
||||
bool removeNode(Node **root, int value) {
|
||||
if (!*root)
|
||||
return false;
|
||||
if (value == (*root)->value) {
|
||||
replace(root, selectChild(*root));
|
||||
if (*root)
|
||||
*root = balanceTree(*root);
|
||||
} else if (!removeChild(root, value))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool removeChild(Node **root, int value) {
|
||||
Node **child = (value < (*root)->value) ? &(*root)->lt : &(*root)->gt;
|
||||
|
||||
if (!*child)
|
||||
return false;
|
||||
if ((*child)->value == value)
|
||||
replace(child, selectChild(*child));
|
||||
else if (!removeChild(child, value))
|
||||
return false;
|
||||
*root = balanceTree(*root);
|
||||
return true;
|
||||
}
|
||||
|
||||
void replace(Node **root, Node *newRoot) {
|
||||
free(*root);
|
||||
*root = newRoot;
|
||||
}
|
||||
|
||||
Node *selectChild(Node *root) {
|
||||
if (root->lt) {
|
||||
if (!root->gt)
|
||||
return root->lt;
|
||||
return selectByValue(root);
|
||||
}
|
||||
return root->gt;
|
||||
}
|
||||
|
||||
Node *selectByValue(Node *root) {
|
||||
Node *parent = root, *child = findMaxValue(&parent, root->lt);
|
||||
|
||||
rearrangePointers(root, parent, child);
|
||||
return child;
|
||||
}
|
||||
|
||||
Node *findMaxValue(Node **parent, Node *child) {
|
||||
if (!child->gt)
|
||||
return child;
|
||||
*parent = child;
|
||||
return findMaxValue(parent, child->gt);
|
||||
}
|
||||
|
||||
void rearrangePointers(Node *root, Node *parent, Node *child) {
|
||||
child->gt = root->gt;
|
||||
if (root == parent)
|
||||
return;
|
||||
parent->gt = child->lt;
|
||||
child->lt = root->lt;
|
||||
}
|
||||
|
||||
bool destroyTree(Node **root) {
|
||||
if (!*root)
|
||||
return false;
|
||||
destroy(*root);
|
||||
*root = NULL;
|
||||
return true;
|
||||
}
|
||||
|
||||
void destroy(Node *root) {
|
||||
if (root->lt)
|
||||
destroy(root->lt);
|
||||
if (root->gt)
|
||||
destroy(root->gt);
|
||||
free(root);
|
||||
}
|
||||
|
||||
/* Tree balancing */
|
||||
|
||||
Node *balanceTree(Node *root) {
|
||||
int balance = getBalance(root);
|
||||
|
||||
/* Left heavy */
|
||||
if (balance > 1) {
|
||||
if (getBalance(root->lt) < 0)
|
||||
root->lt = rotateLeft(root->lt);
|
||||
return rotateRight(root);
|
||||
}
|
||||
|
||||
/* Right heavy */
|
||||
if (balance < -1) {
|
||||
if (getBalance(root->gt) > 0)
|
||||
root->gt = rotateRight(root->gt);
|
||||
return rotateLeft(root);
|
||||
}
|
||||
|
||||
updateHeight(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
int getBalance(Node *root) { return height(root->lt) - height(root->gt); }
|
||||
|
||||
int height(Node *root) { return (root) ? root->height : -1; }
|
||||
|
||||
void updateHeight(Node *root) {
|
||||
root->height = MAX(height(root->lt), height(root->gt)) + 1;
|
||||
}
|
||||
|
||||
Node *rotateLeft(Node *root) {
|
||||
Node *newRoot = root->gt, *child = newRoot->lt;
|
||||
|
||||
newRoot->lt = root;
|
||||
root->gt = child;
|
||||
|
||||
updateHeight(root);
|
||||
updateHeight(newRoot);
|
||||
return newRoot;
|
||||
}
|
||||
|
||||
Node *rotateRight(Node *root) {
|
||||
Node *newRoot = root->lt, *child = newRoot->gt;
|
||||
|
||||
newRoot->gt = root;
|
||||
root->lt = child;
|
||||
|
||||
updateHeight(root);
|
||||
updateHeight(newRoot);
|
||||
return newRoot;
|
||||
}
|
||||
|
||||
/* Printing output */
|
||||
|
||||
void preOrder(Node *root) {
|
||||
if (!root)
|
||||
return;
|
||||
printf("%d ", root->value);
|
||||
preOrder(root->lt);
|
||||
preOrder(root->gt);
|
||||
}
|
||||
|
||||
void inOrder(Node *root) {
|
||||
if (!root)
|
||||
return;
|
||||
inOrder(root->lt);
|
||||
printf("%d ", root->value);
|
||||
inOrder(root->gt);
|
||||
}
|
||||
|
||||
Node *kthNode(Node *root, int *index, int k) {
|
||||
Node *lt;
|
||||
|
||||
if (!root)
|
||||
return root;
|
||||
lt = kthNode(root->lt, index, k);
|
||||
if (lt)
|
||||
return lt;
|
||||
if (++(*index) == k)
|
||||
return root;
|
||||
return kthNode(root->gt, index, k);
|
||||
}
|
||||
|
||||
int getValue(Node *root, int k) {
|
||||
int i = -1;
|
||||
Node *n = kthNode(root, &i, k);
|
||||
|
||||
if (n)
|
||||
return n->value;
|
||||
return EOF;
|
||||
}
|
||||
|
||||
#endif
|
|
@ -0,0 +1 @@
|
|||
Subproject commit d4a659215ec8a9097e0bf8d670200112afd92dc3
|
After Width: | Height: | Size: 21 KiB |
After Width: | Height: | Size: 26 KiB |
After Width: | Height: | Size: 24 KiB |
After Width: | Height: | Size: 28 KiB |
After Width: | Height: | Size: 23 KiB |
After Width: | Height: | Size: 28 KiB |
After Width: | Height: | Size: 23 KiB |
|
@ -0,0 +1,27 @@
|
|||
#include "./merge_select.h"
|
||||
|
||||
int main () {
|
||||
int i = 0, size, index;
|
||||
array A;
|
||||
|
||||
if (!scanf(" %d", &size) || size < 1 || size > INT_MAX) {
|
||||
printf("Tamanho inválido: não se encontra desde 1 a %d.\n", INT_MAX);
|
||||
return 1;
|
||||
}
|
||||
A = malloc(size * sizeof(int));
|
||||
while (i < size && scanf(" %d", A + i))
|
||||
i++;
|
||||
if (i < size) {
|
||||
printf("Lista mal formatada: apenas %d valores foram encontrados.\n", i);
|
||||
return 1;
|
||||
}
|
||||
if (!scanf(" %d", &index) || index < 1 || index >= size) {
|
||||
printf("Índice invalido: não se encontra desde 1 a %d.\n", size);
|
||||
return 1;
|
||||
}
|
||||
|
||||
mergeSort(A, size);
|
||||
printf("O %dº elemento de menor valor: %d\n", index, A[index - 1]);
|
||||
free(A);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
#include "./merge_select.h"
|
||||
|
||||
int * readArray (int *size) {
|
||||
int d, i = 0;
|
||||
char c;
|
||||
array A;
|
||||
|
||||
*size = 1;
|
||||
A = malloc(sizeof(int));
|
||||
do {
|
||||
if (!scanf(" %d", &d))
|
||||
continue;
|
||||
if (i == *size - 1) {
|
||||
*size *= 2;
|
||||
A = realloc(A, *size * sizeof(int));
|
||||
}
|
||||
A[i++] = d;
|
||||
} while ((c = getchar()) != EOF && c != '\n');
|
||||
*size = i;
|
||||
return A;
|
||||
}
|
||||
|
||||
int main () {
|
||||
int i, d, size;
|
||||
array A;
|
||||
|
||||
printf("Este programa admite uma lista de valores inteiros x tais que %d ≤ x ≤ %d e afere o valor do i-ésimo menor valor.\nDigite uma série de valores inteiros separadas entre si por espaço e pressione ENTER:\n", INT_MIN, INT_MAX);
|
||||
A = readArray(&size);
|
||||
|
||||
printf("Digite um índice i tal que 1 ≤ i ≤ %d: ", size);
|
||||
if (!scanf(" %d", &d) || d <= 0 || d > size) {
|
||||
printf("Valor inválido detectado.\n");
|
||||
return 1;
|
||||
}
|
||||
mergeSort(A, size);
|
||||
|
||||
printf("Arranjo ordenado:\n");
|
||||
for (i = 0; i < size; i++)
|
||||
printf("%d ", A[i]);
|
||||
printf("\n");
|
||||
|
||||
printf("\nO %dº elemento de menor valor: %d\n", d, A[d - 1]);
|
||||
free(A);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <limits.h>
|
||||
#define array int*
|
||||
#include "./merge_sort.c"
|
||||
|
||||
void merge (array A, int pivot, int size);
|
||||
void mergeSort (array A, int size);
|
|
@ -0,0 +1,25 @@
|
|||
#include <stdlib.h>
|
||||
#define array int*
|
||||
|
||||
void merge (array A, int pivot, int size) {
|
||||
int i, k, j = pivot;
|
||||
array tmp = malloc(size * sizeof(int));
|
||||
|
||||
for (i = k = 0; k < size; k++)
|
||||
tmp[k] = ((A[i] <= A[j] && i < pivot) || j == size) ?
|
||||
A[i++] : A[j++];
|
||||
for (k = 0; k < size; k++)
|
||||
A[k] = tmp[k];
|
||||
free(tmp);
|
||||
}
|
||||
|
||||
void mergeSort (array A, int size) {
|
||||
int pivot;
|
||||
|
||||
if (size <= 1)
|
||||
return;
|
||||
pivot = size / 2;
|
||||
mergeSort(A, pivot);
|
||||
mergeSort(A + pivot, size - pivot);
|
||||
merge(A, pivot, size);
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
#include "./quick_select.h"
|
||||
|
||||
int main () {
|
||||
int i = 0, size, index;
|
||||
array A;
|
||||
|
||||
if (!scanf(" %d", &size) || size < 1 || size > INT_MAX) {
|
||||
printf("Tamanho inválido: não se encontra desde 1 a %d.\n", INT_MAX);
|
||||
return 1;
|
||||
}
|
||||
A = malloc(size * sizeof(int));
|
||||
while (i < size && scanf(" %d", A + i))
|
||||
i++;
|
||||
if (i < size) {
|
||||
printf("Lista mal formatada: apenas %d valores foram encontrados.\n", i);
|
||||
return 1;
|
||||
}
|
||||
if (!scanf(" %d", &index) || index < 1 || index >= size) {
|
||||
printf("Índice invalido: não se encontra desde 1 a %d.\n", size);
|
||||
return 1;
|
||||
}
|
||||
printf("O %dº elemento de menor valor: %d\n", index, *(quickSelect(A, size, index - 1)));
|
||||
free(A);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
#include "./quick_select.h"
|
||||
|
||||
int * readArray (int *size) {
|
||||
int d, i = 0;
|
||||
char c;
|
||||
array A;
|
||||
|
||||
*size = 1;
|
||||
A = malloc(sizeof(int));
|
||||
do {
|
||||
if (!scanf(" %d", &d))
|
||||
continue;
|
||||
if (i == *size - 1) {
|
||||
*size *= 2;
|
||||
A = realloc(A, *size * sizeof(int));
|
||||
}
|
||||
A[i++] = d;
|
||||
} while ((c = getchar()) != EOF && c != '\n');
|
||||
*size = i;
|
||||
return A;
|
||||
}
|
||||
|
||||
int main () {
|
||||
int i, size, d, *result;
|
||||
array A;
|
||||
|
||||
printf("Este programa admite uma lista de valores inteiros x tais que %d ≤ x ≤ %d e afere o valor do i-ésimo menor valor.\nDigite uma série de valores inteiros separadas entre si por espaço e pressione ENTER:\n", INT_MIN, INT_MAX);
|
||||
A = readArray(&size);
|
||||
|
||||
printf("Digite um índice i tal que 1 ≤ i ≤ %d: ", size);
|
||||
if (!scanf(" %d", &d) || d <= 0 || d > size) {
|
||||
printf("Valor inválido detectado.\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
result = quickSelect(A, size, d - 1);
|
||||
|
||||
printf("\nArranjo parcialmente ordenado:\n");
|
||||
for (i = 0; i < size; i++)
|
||||
printf("%d ", A[i]);
|
||||
printf("\n");
|
||||
|
||||
printf("\nO %dº elemento de menor valor: %d\n", d, *result);
|
||||
free(A);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
#define array int*
|
||||
|
||||
void swap (int *a, int *b) {
|
||||
int tmp = *a;
|
||||
*a = *b;
|
||||
*b = tmp;
|
||||
}
|
||||
|
||||
int partition (array A, int pivot, int size) {
|
||||
int i, j, lastIndex = size - 1;
|
||||
|
||||
swap(&A[pivot], &A[lastIndex]);
|
||||
for (i = j = 0; i < lastIndex; i++)
|
||||
if (A[i] <= A[lastIndex])
|
||||
swap(&A[i], &A[j++]);
|
||||
swap(&A[i], &A[j]);
|
||||
return j;
|
||||
}
|
||||
|
||||
int * quickSelect (array A, int size, int i) {
|
||||
int pivot;
|
||||
|
||||
if (size <= 1)
|
||||
return A;
|
||||
pivot = partition(A, i, size);
|
||||
if (pivot == i)
|
||||
return A + i;
|
||||
if (i < pivot)
|
||||
return quickSelect(A, pivot, i);
|
||||
pivot++;
|
||||
return quickSelect(A + pivot, size - pivot, i - pivot);
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <limits.h>
|
||||
#define array int*
|
||||
#include "./quick_select.c"
|
||||
|
||||
void swap (int *a, int *b);
|
||||
int partition (array A, int pivot, int size);
|
||||
int * quickSelect (array A, int size, int i);
|
|
@ -0,0 +1,73 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/param.h>
|
||||
|
||||
typedef struct item {
|
||||
int value, weight;
|
||||
} Item;
|
||||
|
||||
Item * initializeList (int size) {
|
||||
int i;
|
||||
Item *list = malloc(size * sizeof(Item));
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
scanf(" %d", &list[i].weight);
|
||||
for (i = 0; i < size; i++)
|
||||
scanf(" %d", &list[i].value);
|
||||
return list;
|
||||
}
|
||||
|
||||
int ** initializeTable (Item *list, int size, int capacity) {
|
||||
int i, j, **results = malloc(++size * sizeof(int*));
|
||||
|
||||
results[0] = calloc(++capacity, sizeof(int));
|
||||
for (i = 1; i < size; i++) {
|
||||
results[i] = malloc(capacity * sizeof(int));
|
||||
for (j = 0; j < capacity; j++)
|
||||
results[i][j] = (list[i - 1].weight > j) ? results[i - 1][j] : MAX(results[i - 1][j], list[i - 1].value + results[i - 1][j - list[i - 1].weight]);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
void outputSelection (Item *list, int **results, int size, int capacity) {
|
||||
int i = -1, total = 0, *index = malloc(size * sizeof(int));
|
||||
|
||||
while (size > 0) {
|
||||
if (results[size][capacity] != results[size - 1][capacity]) {
|
||||
capacity -= list[size - 1].weight;
|
||||
total += list[size - 1].value;
|
||||
index[++i] = size - 1;
|
||||
}
|
||||
free(results[size--]);
|
||||
}
|
||||
free(*results);
|
||||
free(results);
|
||||
|
||||
while (i >= 0) {
|
||||
printf("Item: %-5d Valor: %5d Peso: %5d Razão: %f\n",
|
||||
index[i] + 1, list[index[i]].value, list[index[i]].weight,
|
||||
(float) list[index[i]].value / list[index[i]].weight);
|
||||
i--;
|
||||
}
|
||||
free(list);
|
||||
free(index);
|
||||
|
||||
printf("Capacidade restante da mochila: %d\n", capacity);
|
||||
printf("Valor total armazenado: %d\n", total);
|
||||
}
|
||||
|
||||
void dynamicKnapsack (Item *list, int size) {
|
||||
int capacity;
|
||||
|
||||
scanf(" %d", &capacity);
|
||||
printf("Capacidade da mochila: %d\nConteúdos:\n", capacity);
|
||||
outputSelection(list, initializeTable(list, size, capacity), size, capacity);
|
||||
}
|
||||
|
||||
int main () {
|
||||
int size;
|
||||
|
||||
scanf(" %d", &size);
|
||||
dynamicKnapsack(initializeList(size), size);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
typedef struct item {
|
||||
unsigned int index, value, weight;
|
||||
float ratio;
|
||||
} Item;
|
||||
|
||||
Item * initializeList (unsigned int size) {
|
||||
unsigned int i;
|
||||
Item *list = malloc(size * sizeof(Item));
|
||||
|
||||
for (i = 0; i < size; i++) {
|
||||
list[i].index = i;
|
||||
scanf(" %u", &list[i].weight);
|
||||
}
|
||||
for (i = 0; i < size; i++) {
|
||||
scanf(" %u", &list[i].value);
|
||||
list[i].ratio = (float) list[i].value / list[i].weight;
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
void swap (Item *a, Item *b) {
|
||||
Item tmp = *a;
|
||||
*a = *b;
|
||||
*b = tmp;
|
||||
}
|
||||
|
||||
int partition (Item *list, unsigned int size) {
|
||||
unsigned int i, j, lastIndex = size - 1;
|
||||
|
||||
for (i = j = 0; i < lastIndex; i++)
|
||||
if (list[i].ratio >= list[lastIndex].ratio)
|
||||
swap(&list[i], &list[j++]);
|
||||
swap(&list[i], &list[j]);
|
||||
return j;
|
||||
}
|
||||
|
||||
void quickSort (Item *list, unsigned int size) {
|
||||
unsigned int pivot;
|
||||
|
||||
if (size <= 1)
|
||||
return;
|
||||
pivot = partition(list, size);
|
||||
quickSort(list, pivot++);
|
||||
quickSort(list + pivot, size - pivot);
|
||||
}
|
||||
|
||||
void greedyKnapsack (Item *list, unsigned int size) {
|
||||
unsigned int i, capacity, total = 0;
|
||||
|
||||
scanf(" %u", &capacity);
|
||||
printf("Capacidade da mochila: %u\nConteúdos:\n", capacity);
|
||||
for (i = 0; i < size; i++) {
|
||||
if (list[i].weight > capacity)
|
||||
continue;
|
||||
capacity -= list[i].weight;
|
||||
total += list[i].value;
|
||||
printf("Item: %-5u Valor: %5u Peso: %5u Razão: %f\n",
|
||||
list[i].index + 1, list[i].value, list[i].weight, list[i].ratio);
|
||||
}
|
||||
printf("Capacidade restante da mochila: %u\n", capacity);
|
||||
printf("Valor total armazenado: %u\n", total);
|
||||
}
|
||||
|
||||
int main () {
|
||||
unsigned int size;
|
||||
Item *list;
|
||||
|
||||
scanf(" %u", &size);
|
||||
list = initializeList(size);
|
||||
quickSort(list, size);
|
||||
greedyKnapsack(list, size);
|
||||
free(list);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
50
|
||||
309
|
||||
284
|
||||
604
|
||||
992
|
||||
751
|
||||
342
|
||||
56
|
||||
138
|
||||
421
|
||||
493
|
||||
400
|
||||
299
|
||||
694
|
||||
711
|
||||
94
|
||||
763
|
||||
74
|
||||
451
|
||||
326
|
||||
747
|
||||
456
|
||||
463
|
||||
983
|
||||
219
|
||||
439
|
||||
676
|
||||
112
|
||||
812
|
||||
262
|
||||
382
|
||||
206
|
||||
535
|
||||
124
|
||||
805
|
||||
426
|
||||
122
|
||||
154
|
||||
943
|
||||
996
|
||||
825
|
||||
411
|
||||
208
|
||||
208
|
||||
749
|
||||
625
|
||||
730
|
||||
543
|
||||
541
|
||||
677
|
||||
264
|
||||
307
|
||||
501
|
||||
222
|
||||
303
|
||||
855
|
||||
735
|
||||
830
|
||||
88
|
||||
733
|
||||
786
|
||||
558
|
||||
228
|
||||
590
|
||||
928
|
||||
393
|
||||
441
|
||||
66
|
||||
921
|
||||
683
|
||||
8
|
||||
147
|
||||
496
|
||||
665
|
||||
649
|
||||
931
|
||||
468
|
||||
654
|
||||
895
|
||||
694
|
||||
302
|
||||
647
|
||||
874
|
||||
38
|
||||
286
|
||||
753
|
||||
437
|
||||
836
|
||||
631
|
||||
518
|
||||
299
|
||||
181
|
||||
630
|
||||
690
|
||||
410
|
||||
967
|
||||
872
|
||||
738
|
||||
10
|
||||
83
|
||||
894
|
||||
1350
|