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!
>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;
}