Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Alternative way to to write `array[top–]` in a code?

I am self studying data structures and algorithms for some times. I found the following code snippet in stack data structure, pop operation implementation in java.

    public int pop() {
       if (isEmpty()){
//          System.exit(1);
            System.out.println("Stack is full");
            return 0;
        }
        return array[top--];
    }

It is clear to me that the code line return array[top--]; remove the top most element of the stack by decrementing top level of the stack (Top) by 1. Instead of writing the line as given how else I can I write the code in simpler (expanded) way? Can somebody please explain how the return array[top--]; line works?

Thank you in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The postdecrement operator (–) reduces the value (top) but returns the value before the operator was applied.

A more verbose version would be:

public int pop() {
    if (isEmpty()) {
        // ... Error
    }
    int result = array[top];
    top = top - 1;
    return result;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading