1

This procedure Supprimerpremier should delete the first element of the linked list by moving the head pointer to the 2nd element and then disposing the first element it doesn't seem to work.

I don't know why it's not working; when I display the list with the procedure it the list still has 3 elements.

Thanks in advance =)

Program TP1;

Uses crt ;

Type  
      T = ^TT;
      TT = Record    //declaring my list 
        s: String;
        n: Integer;
        nxt: T;
      End;
    Var
      x,p : T ;
    
Procedure Supprimerpremier (L : T); // procedure to delete the first element of my list 
    Var
      x: T;
         iptr: ^integer;
       y: ^word;
    Begin
    x:=L;
    L:=L^.nxt;
    Dispose(x);
    End;

Procedure Afficher (L :T);  //prints the list 
Var
  x: T;
Begin
  x := L;
  While ( x^.nxt<> Nil ) Do //
    Begin
      Writeln;
      Writeln;
      Writeln(x^.s);
      Writeln(x^.n);
      x := x^.nxt;
    End;
  Writeln;
  Writeln;
  Writeln(x^.s);
  Writeln(x^.n);
End;
//

Begin 
           new(p);
              p^.n := 1111;
              p^.s := 'iam the first element';
              new(p^.nxt);
              p^.nxt^.n := 222;
              p^.nxt^.s := 'iam the second element';
              new(p^.nxt^.nxt);
              p^.nxt^.nxt^.n := 778; 
              p^.nxt^.nxt^.s := 'iam the third element ';
              p^.nxt^.nxt^.nxt := Nil;

    Supprimerpremier (p); //
    Afficher (p); 
end;  
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M4hf0d
  • 25
  • 3

1 Answers1

2

You are passing the L parameter by value, so the procedure receives a copy of whatever variable the caller passes in (ie, p). Any modification the procedure makes to the value of L (ie, the L:=L^.nxt; statement) will not be reflected back to the caller's variable.

You need to pass the L parameter by var reference instead, eg:

Procedure Supprimerpremier (var L : T);

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • See also [Pass by reference in Pascal](https://stackoverflow.com/questions/54604999/) and [variable parameter](https://wiki.freepascal.org/Variable_parameter). – AmigoJack Apr 11 '21 at 20:33