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;