Function First element Stack

Asked

Viewed 400 times

0

How do I make a function that returns the first element inserted of a pile?

For example:

i add whole values to my size 5 vector stack.

3
4
5
6
7

You have to return the first element inserted in the stack, in this case the 3.

I made this one:

float retornatopo ( struct Pilha *p ){

if(p->topo < 10)
return p->pElem [p->topo - 1];
else
    return -1;

}

But this return to the top of the stack, I need the first element inserted (FIFO).

  • first in last out - FIFO and last in first out - LIFO

  • So I don’t intend to remove the element, just print on the screen the first element inserted.

  • 1

    The first element would not be pElem[0]?

1 answer

2


You can simply make a function that returns the first element in this way:

float primeiroElemento ( struct Pilha *p ) {
    if( p->topo > 0 )
        return p->Elem[0];

    return -1;
}

The above function checks for elements in the stack, if any returns the first. If no, returns -1;

You can do it this way quietly. But if your goal is pull out the first element and keep the rest of the elements in the same order, me advise against the use of the function I mentioned. In fact, it only returns the value which is in the 0 position of the stack. If you want to remove the element this function does not serve.

  • That was it gave right, until someone understood Mfim first. Congratulations. I always ask questions here keep an eye.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.