Help with pascal lists

0
Procedure Remove(minQuantity:integer; VAR storage: tList);

    var
        p:tPosL;
        d:tItem;
        counter:integer; 
    begin
        p:=first(storage);
        counter:=0;
        writeln('**** Removing ingredients with quantity inferior to ',minQuantity);
        if isEmptyList(storage)=false then begin
            while p<>NULL do begin
                d:=getItem(p,storage);
                if d.quantity < minQuantity then begin
                    writeln('* Ingredient ',d.nIngredient,': ',d.quantity);
                    p:=next(p, storage);
                    deleteAtPosition(previous(p,storage), storage);
                    counter:=counter+1;
                    if isEmptyList(storage) then p:=NULL; //if the list is empty, we make p null
                end
                else p:=next(p, storage);  //in case no ingredient removed, just loop
            end;
            if (counter = 0) then writeln('**** No ingredients found in stock')
            else writeln('**** Number of ingredients removed:',counter);
        end
        else writeln('**** No ingredients found in stock');
    end;

When executing this procedure in pascal with the objective of eliminating 3 ingredients using a static list, it eliminates the ingredients incorrectly while doing so with a dynamic list does it perfectly:

DeleteAtPosition in static list

procedure deleteAtPosition(p:tPosL; VAR l:tList);
        var
            q:tPosL;
        begin
            for q:=p to (l.lastpos-1) do l.data[q]:=l.data[q+1];
            l.lastpos:=l.lastpos-1;
        end;

DeleteAtPosition in dynamic list

procedure deleteAtPosition(p:tPosL; VAR l:tList);
    var
        r:tPosL;
    begin
        if(p=l) then l:=l^.next //if p is firstpos
        else begin
            r:=l;
            while(r^.next<>p) do r:=r^.next; //looks for the given position
            r^.next:=p^.next; //changes next
        end;
        dispose(p) //free memory
    end;
    
asked by Poli Fack 15.06.2017 в 18:47
source

1 answer

0

The problem is that you are handling a variable type tList as if it were a vector, when in reality it is a pointer and tPosL are the addresses to which it points. In your cycle, you read memory positions instead of reading elements of a vector and you handle it as a vector being a pointer. On the other hand, no matter how much you "define" a position as the end of the vector, the dimension of it will not change, because at first you should have defined it from 1 to n positions. In itself, you would be mixing linked list theory with static vectors.

    
answered by 01.06.2018 в 16:32