5
Hello, I need to implement a queue using two stacks, IE, I need to insert an integer on stack 1, and when removing an element all items on stack 1 should be transferred to stack 2, making it look like a queue.
Items on stack 1 can only be transferred if stack 2 is empty, while items should be removed from stack 2.
The code for insertion and removal on stack 1 is as follows:
#include<stdio.h>
#include<stdlib.h>
typedef struct noLista{
int info;
struct noLista *prox;
} Elemento;
Elemento* criarNovo(int Caractere);
Elemento* Push(Elemento *Topo, int Caractere);
Elemento* Pop(Elemento *Topo);
Elemento* Top(Elemento *Topo);
main () {
int Dados, i, op;
Elemento *Pilha = NULL, *aux;
do{
system("cls");
printf("1 - Adicionar elemento\n");
printf("2 - Remover elemento\n");
printf("0 - Encerrar\n\n");
printf("Opcao: ");
scanf("%d", &op);
switch(op){
case 1:
printf("Digite um inteiro: ");
scanf("%d", &Dados);
Pilha = Push(Pilha, Dados);
printf("Elemento adicionado\n\n");
system("pause");
break;
case 2:
aux = Top(Pilha);
if(aux != NULL){
Pilha = Pop(Pilha);
printf("Elemento removido\n\n");
system("pause");
} else{
printf("A pilha esta vazia\n\n");
system("pause");
}
break;
case 3:
break;
}
} while(op!=0);
}
Elemento* criarNovo(int Caractere){
Elemento *novo;
novo = (Elemento*) malloc(sizeof(Elemento));
novo->info = Caractere;
novo->prox = NULL;
return novo;
}
Elemento* Push(Elemento *Topo, int Caractere){
Elemento *novo;
novo = criarNovo(Caractere);
novo->prox = Topo;
Topo = novo;
return Topo;
}
Elemento* Pop(Elemento *Topo){
Elemento *aux;
aux = Topo;
if(Topo != NULL) {
Topo = Topo->prox;
free(aux);
}
return Topo;
}
Elemento* Top(Elemento *Topo){
return Topo;
}
What should I do?
The stack implementations are not very well, I can respond with an implementation "more my way" if you want, because I do not do the functions of
push
,pop
..etc.– Fábio Morais
Fabio, feel free to implement in your own way, I will be grateful.
– Vinícius Rodrigues