Monday, November 9, 2009

13. Link Lists in Free Pascal

Creating Link Lists in Pascal is very easy with pointers.

1.First define the link as a record type. It will have two areas. A data area and a pointer area.
type point = ^link;
link = record
data : integer;
next : point;
end;

2. Define variables for Link Record. We need three pointer variables of type link to track the growth of the List, first, last and current.
var i : integer;
first,last,current : point;

3. Create the Link Record and make it as the current record for linking to the list. If there is no first record, make the current record as first and last records in the List. When we create the next current link , we just replace the last record's next pointer by the current record pointer and make the current record as the last record, effectively increasing the links by 1.

new(current);
current^.data := i;
current^.next := nil;
if first = nil then first := current
else last^.next := current;

last := current;

4. we can create links, display them and dispose them too in this simple way.
for i:= 1 to 10 do
createlinks(i);

Displaylinks;
disposelinks;

5. Program13 follows:



Program program13;
(* Author: Rao S Lakkaraju *)
(* Pointer Basics - Link Lists *)
uses crt,graph;

type point = ^link;
link = record
data : integer;
next : point;
end;

var i,linktot : integer;
first,last,current : point;

Procedure createlinks(i:integer);
begin
new(current);
current^.data := i;
current^.next := nil;
if first = nil then first := current
else last^.next := current;

last := current;
linktot := linktot + 1;

writeln('last data= ', last^.data);

end;

Procedure Displaylinks;
begin

textbackground(white);
textcolor(red);

Current := first;
repeat
write(current^.data, ' ');
current := current^.next;
until current = nil;
end;

Procedure disposelinks;
{ Store next link address and dispose first link}
{Make next link address as first link}
{Repeat until there are no more next links}
begin
repeat
{current := first;}
current := first^.next;
dispose(first);
first := current^.next;
until first = nil;
end;

begin
clrscr;
first := nil;
linktot := 0;

for i:= 1 to 10 do
createlinks(i);

Displaylinks;
disposelinks;

writeln;
writeln('Total Links in the List = ',linktot);
writeln('My thirteenth Pascal program');
readln;
end.


SUMMARY: It is very easy to create links in Pascal. Create a typed record with desired elements in it, the last element should be a pointer to link to the next record. Keep track of first, Last and current records while adding to the List. We will have a linked list in Pascal in no time.

No comments:

Post a Comment