Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Insert and Remove List Elements using C

#include <stdio.h>
#include <stdlib.h>
#define MAX 100

typedef struct pilha {
    int topo;
    int dados[MAX];
} Pilha;

Pilha *criarPilha(void) {
    Pilha *p = (Pilha *) malloc(sizeof(Pilha));
    if (p != NULL) {
        p->topo = 0;
    }
    return p;
}

int eVazia(Pilha *p) {
    if (p->topo == 0){
        return 1;
    } else {
        return 0;
    }
}

Pilha *empilhar(Pilha *p, int valor) {
    if (p == NULL || p->topo == MAX) {
        return p;
    }
    p->dados[p->topo] = valor;
    p->topo++;
    return p;
}

Pilha *desempilhar(Pilha *p) {
    if (p == NULL || p->topo == 0) {
        return p;
    }
    p->topo--;
    return p;
}

int topo(Pilha *p) {
    return p->dados[p->topo - 1];
}

int main()
{
    // criando pilha
    Pilha* minhaPilha;
    minhaPilha = criarPilha();
    
    /*
    empilhar(minhaPilha, 5);
    
    printf("%d \n %d", minhaPilha->topo, minhaPilha->dados[0]);
    */
    
    // inserindo 100 elementos
    int i = 1;
    for (i=1; i<=100; i++) {
        empilhar(minhaPilha, i);
        printf("elemento adicionado = %d \n", topo(minhaPilha));
    }
    
    for (i=0; i<50; i++) {
        printf("elemento removido = %d \n", topo(minhaPilha));
        desempilhar(minhaPilha);
    }
    
    printf("topo da lista = %d \n", topo(minhaPilha));
    
    return 0;
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.