Unwrapping can not return an empty element?

2

Code taken from a Data Structure workbook.

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 in the stack. If I unpick the last item with this method (decreasing 1 in the variable top this.topo--; and returning the info vector with the index at the top decreased return this.info[this.topo]; ) I would not end up returning the last item of the stack instead of unstacking this item?

    
asked by anonymous 15.05.2018 / 21:21

1 answer

1

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

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

    
15.05.2018 / 21:34