Search code examples
c++data-structures

Why length of linear list is decremented, even if the position of the returned value gets replaced by something?


There is a question about linear list in my textbook, and I can't understand the answer code in line 12 that L.length--;.
The question is described as follows:

The element with the smallest value (assumed to be unique) is removed from the order table and the function returns the value of the removed element. The empty position is filled by the last element, and if the sequence table is empty, an error message is displayed and the run is exited.

The answer code:

bool Del_Min(SqList &L,ElemType &value) {
    if(L.length==0)
        return false;
    value=L.data[0];
    int pos=0;
    for(int i=l;i<L.length;i++)
        if(L.data[i]<value){
            value=L.data[i];
            pos=i;
        }
    L.data[pos]=L.data[L.length-1];
    L.length--;
    return true;
}

"The SMALLEST VALUE is replaced by the last element", does it mean the data[pos] element is not deleted but replaced by something else?
Why the code in line 12 then still does L.length--;?


Solution

  • Apart from the special case of zero length (which returns immediatly), the list will always get shorter. That is why there is an unconditional decrement of the list length.

    The the return of the value (in contrast to the boolean return value of success or not) is via a reference parameter value which gets (unwisely, I think) updated potentially several times in the function.

    The position in the list it comes from does then still exist, but does not serve the purpose of storing that removed value anymore.

    To effectively pseudo-delete it, the position gets filled with the last value in the list, which is the one (that would otherwise be) dropping out when the list is considered shorter in total.

    So the gap is filled, the previously last value is saved and the list gets shorter by one.