A pilha é uma das estruturas de dados utilizadas para diversas finalidades na computação. Ela é tida como uma estrutura de dados LIFO (Last in, First out), ou seja, o último elemento que entra na pilha é o primeiro a sair.
No nosso exemplo abaixo reproduzimos as operações:
- PUSH – Insere um elemento na pilha.
- POP – Retira um elemento da pilha.
- DISPLAY – Exibe todos os elementos da pilha.
Nossa STRUCT stack possui duas variáveis:
- stk[MAXSIZE] – Vetor que armazena os valores na pilha. MAXSIZE é uma constante que define o tamanho da pilha.
- top – Variável que armazena a posição do ultimo elemento a entrar na pilha.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
#include <stdio.h> #define MAXSIZE 5 struct stack { int stk[MAXSIZE]; int top; }; typedef struct stack STACK; STACK s; void push(void); int pop(void); void display(void); void main () { int choice; int option = 1; s.top = -1; printf ("OPERAÇÕES DA PILHA\n"); while (option) { printf ("------------------------------------------\n"); printf (" 1 --> PUSH \n"); printf (" 2 --> POP \n"); printf (" 3 --> DISPLAY \n"); printf (" 4 --> SAIR \n"); printf ("------------------------------------------\n"); printf ("Escolha uma opção\n"); scanf ("%d", &choice); switch (choice) { case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: return; } fflush (stdin); printf ("Deseja continuar? (0 para encerrar ou 1 para continuar)\n"); scanf ("%d", &option); } } /* Adiciona elementos na pilha */ void push () { int num; if (s.top == (MAXSIZE - 1)) { printf ("Pilha cheia\n"); return; } else { printf ("Insira o elemento: \n"); scanf ("%d", &num); s.top = s.top + 1; s.stk[s.top] = num; } return; } /* Retira elementos da pilha */ int pop () { int num; if (s.top == - 1) { printf ("Pilha vazia\n"); return (s.top); } else { num = s.stk[s.top]; printf ("Elemento retirado = %dn", s.stk[s.top]); s.top = s.top - 1; } return(num); } /* Exibe os valores da pilha */ void display () { int i; if (s.top == -1) { printf ("Pilha vazia\n"); return; } else { printf ("\n Elementos na pilha: \n"); for (i = s.top; i >= 0; i--) { printf ("%d\n", s.stk[i]); } } printf ("\n"); } |