Introdução à Pilha (Linguagem C)

Algum tempo atrás decidi postar um breve texto que continha conteúdo para introduzir o leitor ao assunto de Listas Ligadas, mas porque estou mencionando isto?

R: Simples, Pilha nada mais é do que uma Lista Ligada, no entanto tratada de uma maneira específica.

E como seria isto?

R: Devemos apenas respeitar duas regras: Inserir e remover nós no final da lista.

Tudo aquilo que vier a seguir não foi copilado, portanto pode conter erros, caso encontre-os apenas deixe um recado nos comentários que procurarei corrigir quando ler.

Considerando a estrutura e as informações desta postagem, iremos exemplificar a inserção de um nó em uma Pilha, chamaremos a função de push.

Inserção (fim da lista)
no *push(struct no *fim, int numero)
{
    struct no *novo;
    novo = (struct no*)malloc(sizeof(struct no));
    novo->numero = numero;
    novo->prox = NULL;
    if(fim == NULL) {
        fim = novo;
    } else {
        fim->prox = novo;
    }
    return (fim);
}
A função anterior irá inserir um novo nó no final da lista, para todo e qualquer caso, pois é uma regra que deve ser respeitada para a criação de uma Pilha, retornará o nó final.

Remoção (fim da lista)
int pop(struct no **raiz, struct no **fim)
{
    int numero = 0;
    if(*raiz == NULL) {
        printf("A pilha esta vazia.\n");
        return numero;
    } else {
        struct no *aux = *raiz;
        if(*raiz == *fim) {
            numero = *raiz->numero;
            free(*raiz);
            *raiz = NULL;
            *fim = NULL;
        } else {
            struct no *aux_antes = *raiz;
            aux = aux->prox;
            while(aux->prox != NULL) {
                aux = aux->prox;
                aux_antes = aux_antes->prox;
            }
            numero = aux_antes->numero;
            aux_antes->prox = NULL;
            *fim = aux_antes;
            free(aux);
        }
    }
    return (numero);
}
A função anterior irá remover um nó do final da lista para todo e qualquer caso, pois é uma regra que deve ser respeitada para a criação de uma Pilha, desta vez precisaremos do nó inicial e final, o nó final será alterado, retornará o valor inteiro do nó removido.

Liked this article? Then leave a comment, follow this blog and subscribe to our RSS feed. Questions, problems, suggestions or translations? Please contact us. Click here for more instructions to make a small donation.

Be the first to comment

All comments are read and moderated before published.

For every comment
- ALL CAPS or grammatical errors will not be tolerated;
- Do not promote other blogs or websites;
- Do not add unnecessary links in the content of your comment;
- If you want to leave your URL, use the OpenID;
- Promote your e-mail only if really needed;
- Threats, insults or attacks are not allowed;
- Your comment must be related to the subject of the article;

Questions?
- Read all the answers;
- Ask if you can not find the answer;

Comments should contain only the following topics:
- Questions;
- Suggestions;
- Thanks;
- Tips related;

Every comment is a personal opinion of the reader. The authors are not responsible for the content of any comments made by the commenter(s). The authors are also not responsible for knowing whether the content of Your comment is breaking the law in other countries or jurisdictions.

  ©Template by Dicas Blogger and customized by Gugatb.

TOP