Unstacking can’t return an empty element?

Asked

Viewed 67 times

2

Code taken from a Data Structure booklet.

public class PilhaContig {
        private Item [] info;
        private int topo;

        public PilhaContig(int qte){
            this.topo = 0;
            this.info = new Item [qte];
        }
        public Item getInfo(){
            return this.info[this.topo-1];
        }
        public int getTopo(){
            return this.topo;
        }
        public boolean eVazia(){
            return (this.topo == 0);
        }
        public boolean eCheia(){
            return (this.topo == this.info.length);
        }
        public boolean empilhar (Item elem){
            if (this.eCheia()) 
                return false;
            else {
                this.info[this.topo]= elem;
                this.topo++;
                return true;
            }   
        }
        public Item desempilhar(){
            if (this.eVazia())
                return null;
            else{
                this.topo--;
                return this.info[this.topo];
            }
        }   

In the stack class the top variable points to the empty memory space above the last item inserted into the stack. If I pop the last item with this method (decreasing 1 at the top variable this.topo--; and returning the vector info with the index at the diminished top return this.info[this.topo];) I wouldn’t end up returning the last item from the stack instead of unpacking that item?

  • 1

    I don’t understand your doubt

  • If the top points to the empty space above the last stack item, I decreasing the top -1, I won’t end up returning the last empty space instead of unpacking 1 item?

  • What is empty space above the last item?

  • The memory space, on top of the last stack item.

1 answer

1


It’s a logical question, just read what you wrote.

The pointer topo is always pointing to the next free position on the stack. When you do the -1 it passes point to the last item and returns it. From then on this item is disregarded because soon after this number is no longer accessible by the algorithm written except to write a new item up there (function empilhar()).

  • I get it. I was thinking that after I used this method, I would have to assign the value 0 or null to the top variable, but as you said the number is no longer accessible and is disregarded. It was clear, thank you!

Browser other questions tagged

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