125k views
5 votes
The following procedure was intended to remove all occurrences of element x from list L. Explain why it doesn't always work and suggest a way to repair the procedure so that it performs its intended task.

procedure delete (x: elementtype; var L: LIST);
var
p: position;
begin
p:= FIRST(L);
while p <> END(L) do begin
if RETRIEVE(p,L) =x then
DELETE(p,L);
p := NEXT(p,L)
end
end; { delete }

User Pacane
by
5.1k points

1 Answer

7 votes

Answer:

The answer is explained below

Step-by-step explanation:

The procedure in the question doesn't work in all the cases. If there are more than one x elements in the List L consecutively then by applying this procedure all the x terms are not deleted because after deleting element x from the List L at position p, the element(suppose this element is also x) at position p+1 moves to position p. But in the above procedure, after deleting x at position p, p it moved forward and the element x at position p after deletion is not checked.

The procedure to remove all the occurrences of element x from List L is given below.

procedure delete ( x: elementtype; var L: LIST );

var

p: position;

begin

p := FIRST(L);

while p <> END(L) do begin

if RETRIEVE(p, L) = x then

DELETE(p, L);

else

p := NEXT(p, L)

end

end; { delete }

The variable p should not be moved forward after deleting an element from the position p. So we place that statement under an else condition.

User Yeshansachithak
by
5.4k points