#include<stdio.h>
#include<stdlib.h>
typedef struct item_p
{
int elemento;
struct item_p *proximo;
} pilhaItem;
typedef struct
{
pilhaItem *raiz;
int tamanho;
} pilha;
pilha* pilha_nova()
{
/* cria pilha */
pilha
*p
= (pilha
*) malloc(sizeof(pilha
)); if(p == NULL)
return NULL;
/* pilha esta' vazia */
p->raiz = NULL;
p->tamanho = 0;
return p;
}
int pilha_tamanho(pilha *p)
{
if (p == NULL)
return -1;
return p->tamanho;
}
int pilha_top(pilha *p)
{
pilhaItem *aux;
if (p == NULL || p->tamanho == 0)
return NULL;
aux = p->raiz;
return aux->elemento;
}
pilhaItem* pilha_novo_elemento(int valor)
{
/* aloca memoria para a estrutura pilhaItem */
pilhaItem
*item
= (pilhaItem
*) malloc(sizeof(pilhaItem
)); if(item == NULL)
return NULL;
/* cria nova string */
item->elemento=valor;
/* item ainda nao tem proximo */
item->proximo = NULL;
return item;
}
void pilha_push(pilha *p, int valor)
{
pilhaItem *novo = NULL;
if (p == NULL || valor == NULL)
return;
/* cria novo item */
novo = pilha_novo_elemento(valor);
if (novo == NULL)
return;
p->tamanho++;
/* inserir no topo da pilha */
/* se a pilha esta vazia */
if (p->raiz == NULL)
{
p->raiz = novo;
return;
}
/* primeiro elemento */
novo->proximo = p->raiz;
p->raiz = novo;
}
void pilha_pop(pilha *p)
{
pilhaItem *curr;
if (p == NULL || p->tamanho == 0)
return;
curr = p->raiz;
p->raiz = curr->proximo;
p->tamanho--;
/* liberta memoria associada ao item removido */
}
main ()
{
int Dados, i, op;
pilha *pilha=pilha_nova();
pilha_push(pilha, 2);
pilha_push(pilha, 4);
pilha_push(pilha, 6);
while(pilha_tamanho(pilha)>0)
{
printf("%d\n", pilha_top
(pilha
)); pilha_pop(pilha);
}
}
I2luY2x1ZGU8c3RkaW8uaD4KI2luY2x1ZGU8c3RkbGliLmg+Cgp0eXBlZGVmIHN0cnVjdCBpdGVtX3AKewogICAgaW50IGVsZW1lbnRvOwogICAgc3RydWN0IGl0ZW1fc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