Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct No{
- int dado;
- struct No *proximo;
- };
- struct Pilha{
- int tamanho;
- struct No *cabeca;
- };
- void iniciaPilha(struct Pilha *pilha){
- pilha->tamanho = 0;
- pilha->cabeca = NULL;
- }
- int tamanhoPilha(struct Pilha *pilha){
- return pilha->tamanho;
- }
- int vaziaPilha(struct Pilha *pilha){
- if(pilha->tamanho == 0){
- return 1;
- }else{
- return 0;
- }
- }
- int topoPilha(struct Pilha *pilha){
- if(vaziaPilha(pilha)) return 0;
- return (pilha->cabeca)->dado;
- }
- int push(struct Pilha *pilha, int valor){
- struct No *novoNo;
- novoNo = malloc(sizeof(struct No));
- if(novoNo == NULL) return 0;
- novoNo->dado = valor;
- novoNo->proximo = pilha->cabeca;
- pilha->cabeca = novoNo;
- pilha->tamanho++;
- return 1;
- }
- int pop(struct Pilha *pilha, int *valor){
- struct No *aux = pilha->cabeca;
- if(vaziaPilha(pilha)) return 0;
- *valor = (pilha->cabeca)->dado;
- pilha->cabeca = aux->proximo;
- free(aux);
- pilha->tamanho--;
- return 1;
- }
- int mostrarPilha(struct Pilha *pilha){
- struct No *aux = pilha->cabeca;
- int i;
- if(vaziaPilha(pilha)){
- return 0;
- }
- printf("Tamanho da pilha: %d elemento(s)\n", pilha->tamanho);
- printf("----------------------------------\n");
- for(i = 0; i < pilha->tamanho; i++){
- printf("\tPOSICAO: %d\n", i + 1);
- printf("\tVALOR: %d\n", aux->dado);
- aux = aux->proximo;
- printf("\n");
- }
- return 1;
- }
- int comparaPilha(struct Pilha *pilha, struct Pilha *pilha_2){
- struct No *aux = pilha->cabeca;
- struct No *aux_2 = pilha_2->cabeca;
- if(pilha->tamanho != pilha_2->tamanho){
- return 0;
- }
- while(aux != NULL){
- if(aux->dado != aux_2->dado){
- return 0;
- }else{
- aux = aux->proximo;
- aux_2 = aux_2->proximo;
- }
- }
- return 1;
- }
- int invertePilha(struct Pilha *pilha){
- struct Pilha aux;
- iniciaPilha(&aux);
- if(vaziaPilha(pilha)) return 0;
- int i;
- //Passa todos os elementos da pilha principal para a auxiliar, invertendo a pilha
- while(vaziaPilha(pilha) != 1){
- pop(pilha, &i);
- push(&aux, i);
- }
- //A pilha principal passa a ser a pilha auxiliar
- pilha->cabeca = aux.cabeca;
- pilha->tamanho = aux.tamanho;
- return 1;
- }
- void destruirPilha(struct Pilha *pilha){
- int i;
- while(vaziaPilha(pilha)){
- pop(pilha, &i);
- }
- }
- int removeValor(struct Pilha *pilha, int valor){
- struct Pilha aux;
- iniciaPilha(&aux);
- int i;
- if(vaziaPilha(pilha)) return 0;
- while(vaziaPilha(pilha) != 1){
- //Se o valor for igual ao fornecido, ele é apenas descartado
- if(topoPilha(pilha) == valor){
- pop(pilha, &i);
- //Senão, é salvo na pilha auxiliar
- }else{
- pop(pilha, &i);
- push(&aux, i);
- }
- }
- //Insere os valores de volta a pilha original
- while(vaziaPilha(&aux) != 1){
- pop(&aux, &i);
- push(pilha, i);
- }
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment