Estrutura de Dados - Torre de Hanoi
Por: Joao POS • 9/7/2026 • Trabalho acadêmico • 345 Palavras (2 Páginas) • 4 Visualizações
#include<stdio.h>
#include<stdlib.h>
typedef struct pilha Pilha;
struct pilha{
int disco;
Pilha *prox;
};
Pilha *empilha(Pilha *p, int disco, int n){
Pilha *novo;
novo = (Pilha *) malloc (sizeof(Pilha));
if(p->disco == n+1){
novo->disco = disco;
novo->prox = NULL;
return novo;
}else{
Pilha *aux;
aux = p;
while(aux->prox != NULL){
aux = aux->prox;
}
novo->disco = disco;
novo->prox = NULL;
aux->prox = novo;
return p;
}
}
int desempilha(Pilha *p, int n){
Pilha *aux;
Pilha *ant;
aux = p;
ant = NULL;
while(aux->prox != NULL){
ant = aux;
aux = aux->prox;
}
if(aux != p){
ant->prox = NULL;
return aux->disco;
}else{
int x = aux->disco;
aux->disco = n+1;
aux->prox = NULL;
return x;
}
}
Pilha *cria(Pilha *p, int n){
Pilha *novo;
novo = (Pilha *) malloc (sizeof(Pilha));
novo->disco = n+1;
novo->prox = NULL;
return novo;
}
void imprimeAux(char l, Pilha *p, int n){
Pilha *aux;
aux = p;
printf("\n%c|", l);
while(aux != NULL){
if(aux->disco == n+1){
printf(" ", aux->disco);
}else{printf("%d ", aux->disco);}
aux = aux->prox;
}
}
void imprime(Pilha *a, Pilha *b, Pilha *c, int n){
imprimeAux('A', a, n);
imprimeAux('B', b, n);
imprimeAux('C', c, n);
}
Pilha *caminha(Pilha *p){
while(p->prox != NULL){
p = p->prox;
}
return p;
}
void liberar(Pilha *p){
Pilha *aux;
aux = p;
while(p->prox != NULL){
aux = p;
p = p->prox;
free(aux);
}
free(p);
}
void resolverHanoi(int n, Pilha* a, Pilha* b, Pilha* c){
char O = 'z', D = 'z';
Pilha *auxA = a;
Pilha *auxB = b;
Pilha *auxC = c;
auxA = caminha(auxA);
auxB = caminha(auxB);
auxC = caminha(auxC);
do{
...