Problems with this stack implementation

Posted by Andersson Melo on Stack Overflow See other posts from Stack Overflow or by Andersson Melo
Published on 2010-04-10T06:30:10Z Indexed on 2010/04/10 6:33 UTC
Read the original article Hit count: 533

Filed under:
|
|

where is the mistake?

My code here:

 typedef struct _box
    {
        char *dados;
        struct _box * proximo;
    } Box;

    typedef struct _pilha
    {
        Box * topo;
    }Stack;

void Push(Stack *p, char * algo)
{
    Box *caixa;
    if (!p)
    {
        exit(1);
    }

    caixa = (Box *) calloc(1, sizeof(Box));
    caixa->dados = algo;
    caixa->proximo = p->topo;
    p->topo = caixa;
}


char * Pop(Stack *p)
{
    Box *novo_topo;
    char * dados;
    if (!p)
    {
        exit(1);
    }

    if (p->topo==NULL)
        return NULL;

    novo_topo = p->topo->proximo;

    dados = p->topo->dados;

    free(p->topo);
    p->topo = novo_topo;

    return dados;
}


void StackDestroy(Stack *p)
{
    char * c;
    if (!p)
    {
        exit(1);
    }
    c = NULL;
    while ((c = Pop(p)) != NULL)
    {
        free(c);
    }
    free(p);
}

int main()
{
    int conjunto = 1;
    char p[30];
    int flag = 0;

    Stack *pilha = (Stack *) calloc(1, sizeof(Stack));

    FILE* arquivoIN = fopen("L1Q3.in","r");
    FILE* arquivoOUT = fopen("L1Q3.out","w");

    if (arquivoIN == NULL)
    {
        printf("Erro na leitura do arquivo!\n\n");
        exit(1);
    }

    fprintf(arquivoOUT,"Conjunto #%d\n",conjunto);

    while (fscanf(arquivoIN,"%s", p) != EOF )
    {
        if (pilha->topo == NULL && flag != 0)
        {
            conjunto++;
            fprintf(arquivoOUT,"\nConjunto #%d\n",conjunto);
        }

        if(strcmp(p, "return") != 0)
        {
            Push(pilha, p);
        }    
        else
        {
            p = Pop(pilha);

            if(p != NULL)
            {
                fprintf(arquivoOUT, "%s\n", p);
            }
        }
        flag = 1;
    }

    StackDestroy(pilha);

    return 0;
}

The Pop function returns the string value read from file. But is not correct and i don't know why.

© Stack Overflow or respective owner

Related posts about c

    Related posts about stack