Using recycling in Pascal

Say I have a linked list in Pascal. The type will look something like this:

type
  PList = ^TList;
  TList = record
          x: integer;
          Next: PList;
          end;

var
  myList :PList;

So, if I use dispose(myList), then all pointers will be placed in myList? Or just the first one pointing to the first element of myList?

+4
source share
1 answer

No, an order myList(which should be of the type, by the PListway) will destroy only the first element in the list. This is because the compiler knows nothing about how you use individual fields in a record.

For example, you can use a skip list or a doubly linked list, both of which will require two pointers inside an entry.

.

    var myList, listPtr, nextPtr : PList;
    :
    listPtr := myList;            (* start at start, obviously *)
    myList := nil;                (* mark list as empty        *)
    while listPtr <> nil do       (* continue until end        *)
    begin
        nextPtr := listPtr^.next; (* save pointer to next      *)
        dispose (listPtr);        (* kill current              *)
        listPtr := nextPtr;       (* move to next              *)
    end;

, , , , , . dispose.

, , , .

Program TestProg(output);
    type
        PList = ^TList;
        TList = record
            num : integer;
            next: PList;
        end;

    var
        myList  : PList;
        listPtr : PList;
        nextPtr : PList;
begin
    (* Construct list 42 -> 99 -> 12 -| *)

    new (myList);
    new (myList^.next);
    new (myList^.next^.next);
    myList^.next^.next^.next := nil;

    myList^.num := 42;
    myList^.next^.num := 99;
    myList^.next^.next^.num := 12;

    (* Traverse list *)

    listPtr := myList;
    while listPtr <> nil do
    begin
        writeln (listptr^.num);
        listPtr := listPtr^.next;
    end;

    (* Clear list *)

    listPtr := myList;
    while listPtr <> nil do
    begin
        nextPtr := listPtr^.next;
        dispose (listPtr);
        listPtr := nextPtr;
    end;
    myList := nil;
end.
+1

All Articles