Board index » delphi » still having probs with linked list

still having probs with linked list

I am having problems trying to implement a linked list into my program. I
have written several procedures that are suppose to sort a linked list while
I'm entering info. problem is I keep getting an error, and I can't seem to
figure out how to fix it. Number 1 thing for me is to get the program to
run. It's suppose to get input from a user (it's a database type program)
take all the info, and write it to a binary file. Now the fun part, I am to
then take the input and sort it in a linked list then save it to the binary
file when I'm done. Also, how do I delete a node that's pointing to a
record?
So if anyone can help me thanks.

Also please tell me if I got the pointers correct. Thanks

Program Assign4;

uses CRT, graph;

Type bookin=RECORD
     title:string[30];
     AuthorLastName:string[15];
     AuthorFirstName:string[15];
     Publisher:string[25];
     ISBN:string[13];
end;

bookfiletype=FILE of bookin;

bookptr=^booknode;

booknode=RECORD
bookinv:bookin;
next:bookptr;
end;

var
   bookfile:bookfiletype;
   book:bookin;
   head:bookptr;

{ Procedure Border
}
Procedure border{Draws the border for the menu or whenever required};

var
tempvar:integer;                                   {using tempvar as a
counter}
begin

Begin
clrscr
end;

textcolor(yellow);                                 {sets text colour to
yellow}

for tempvar:= 19 to 68 do
begin
gotoxy(tempvar,8);
write('')
end;

for tempvar:=9 to 17 do
begin
gotoxy(18,tempvar);     {Puts cursor at specific point on screen anywhere
                        from 2 - 24 on the Y Axis}
write('o')
end;

for tempvar:=9 to 17 do
begin
gotoxy(69,tempvar);
write('o')
end;

for tempvar:=19 to 68 do
begin
gotoxy(tempvar,18);       {same as previous gotoxy, instead now on X Axis}
write('');
end;

gotoxy(18,8);
write('');
gotoxy(69,8);
write('?');
gotoxy(69,18);
write('?');
gotoxy(18,18);
write('')
end;

Procedure Creatnewnode(VAR link:bookptr; nametoinsert:bookinv);
{Purpose:creates a new node for the name passed in. Ini the NEXT pointer
in the new node to nil}
begin
NEW(link);
link^.book:=nametoinsert;
link^.next:=nil
end;

Procedure findspot(VAR Current, past:bookptr; nametofind:bookfile;)
{search the link list for the right spot to place nametofind in alphabetical
order. when the procedure finishes the current pointer will be pointint to
the node that will come after the new one}
VAR found:boolean;
begin
     found:=false;
                  while((current<>nil) and (not found)) DO
                  begin
                       if nametofind<current^.book then
                          found:=true

                          else
                          begin
                          past:=current;
                          current:=current^.book
                          end
                  end
end;

Procedure InsertNode(VAR Head:NamePtr; NameToInsert:NameString);
{calls findspot to locate the right place in the linked list to isnert a
new name. calls createnewnode to set up a new node with the name and the
next pointer set to nil. Links the new node between the node pointed to
by past and the node pointed to by current.}

VAR Past,Current,Link:Bookptr;

begin
current:=head;          {init pointers}
past:=nil;
Findspot(current,past,nametoinsert);    {find right spot on list}
createnewnode(link,nametoinsert);       {use link for the new node}
link^.next:=current;                    {point new node to the one that will
                                        come after it}

If past=nil then                        {we're inserting at the head of the
list}
   head:=link                           {point head to the new first node}
else                                    {we're inserting in the middle of at
the end}
past^.next:=link                        {put the now node in between}
end;

{ Procedure Record Add
}
{Procedure called by addrec to add records to file}

procedure recad;
var
response:char;

begin{begin recad procedure}
             readln;                            {Used to clear keyboard
buffer}
             repeat
              clrscr;
              seek(bookfile,filesize(bookfile));          {Locates end of
file}
              write('Please enter book title:  ');
              readln(book.title);
              write('Please enter Author''s Last name:  ');
              readln(book.authorlastname);
              write('Please enter Author''s First name:  ');
              readln(book.authorfirstname);
              write('Please enter Publisher:  ');
              readln(book.publisher);
              write('Please enter ISBN:  ');
              readln(book.ISBN);
              insertnode(head,booktitle);{passes head pointer to the name}
              write(head^.bookfile,book);                {Writes all entries
to file}
              write('Add another record (Y/N)?');
              readln(response);
              until (response='N') or (response='n') {Waits for correct
response
                                                     to continue}
end;{end procedure recad}

{ Procedure Addrec
}
{Gets into to add to output file}
procedure addrec;
          var
          infile:string;
          titlein:string;
          errorcode:integer;
          response:char;

 begin{begin addrec}

     readln;
     clrscr;                                                    {clears
screen}
     border;                            {Calls procedure border to draw
border}
     gotoxy(20,13);
     writeln('Please enter desired file name');
     gotoxy(20,14);
     write('(eg:FILENAME.DAT):  ');
     read(infile);
     assign(bookfile,infile);             {assigns infile var to bookfile
name}
     {$I-}                                            {turns off file
checking}
     reset(bookfile);                                  {opens files to be
read}
     Errorcode:=IORESULT;                                     {sets error
code}
     {$I+}                                             {turns on file
checking}
          if errorcode = 0 then                    {Checks if error code is
ok}
             begin
             recad                                      {Calls procedure
recad}
             end
          else
              begin
              rewrite(bookfile);                   {Creates and opens new
file}
              recad
              end
 end;

{ Procedure Listin
}
{Procedure listin, Lists all records in specified file}

procedure listin;
          var
          infile:string;
          page:integer;
          errorcode:integer;
          x,y:integer;
          remain:integer;

 begin    {begin listin}
      clrscr;
      readln;
      border;
      gotoxy(20,10);
      writeln('Please enter file name to view ');
      gotoxy(20,11);
      write('contents (eg: FILESNAME.DAT):  ');
      readln(infile);
      assign(bookfile,infile);
      textcolor(white);
      clrscr;
             {$I-}
             reset(bookfile);
             errorcode:=IORESULT;
             {$I+}

                  if errorcode=2 then
                     begin
                          clrscr;
                          writeln('File ',infile,' doesn''t exist');
                     end
                  else
                      begin
                           page:=0;
                           x:=1;
                           y:=1;
                           remain:=filesize(bookfile);
                      while not EOF( bookfile ) do
                           with book do
                                begin
                                 if page = 4 then       {Sets counter to
                                                         count up to 4
                                                         to display 4 record
                                                         on screen at 1
time}
                                 begin
                                 page:=0;
                                 remain:=remain-4;      {sets counter to
remain
                                                        to subtract 4 from
                                                        remaining records in
                                                        file}
                                 textcolor(yellow);
                                 write('Press ENTER to view next ');
                                 textcolor(lightcyan);
                                 write(remain);
                                 textcolor(yellow);
                                 write(' records.');
                                 readln;
                                 clrscr
                                end
                                 else
                                  begin
                                  page:=page+1;
                                  read(bookfile,book);
                                  textcolor(white);
                                  write('              Title:  ');
                                  writeln(title);
                                  write(' Author''s Last Name:  ');
                                  writeln(authorlastname);
                                  write('Author''s First Name:  ');
                                  writeln(authorfirstname);
                                  write('          Publisher:  ');
                                  writeln(publisher);
                                  write('               ISBN:  ');
                                  writeln(ISBN);
                                  writeln
...

read more »

 

Re:still having probs with linked list


hi heero

multiple problems in your code and explanation too...

"Heero Yuy" <blade16...@canada.com> schrieb im Newsbeitrag news:7diT5.18488$sz3.3704110@news1.telusplanet.net...

Quote
> I am having problems trying to implement a linked list into my program. I
> have written several procedures that are suppose to sort a linked list while
> I'm entering info.

this makes me believe you always have to keep a sorted list (sorted by what?)

Quote
>  problem is I keep getting an error, and I can't seem to
> figure out how to fix it. Number 1 thing for me is to get the program to
> run.

this is not #1,
#1 is:  you always should know what you're doing.
vice versa:
"Comment out all the code which causes error and you'll get running code"
;-)

Quote
> It's suppose to get input from a user (it's a database type program)
> take all the info, and write it to a binary file.
> Now the fun part, I am to
> then take the input and sort it in a linked list then save it to the binary
> file when I'm done.

right here your're telling us, the database has to be sorted again.
(resorted by a new item ?)

Quote
>Also, how do I delete a node that's pointing to a record?

dispose(!)

deleting a record within a file is not possible without rewriting the file.

Quote
> So if anyone can help me thanks.

> Also please tell me if I got the pointers correct. Thanks

as far as i've read the sources of your postings (just some of your procedures),
you still have to learn things about fileIO / pointers and even declarations and visibitlity.

to start with, you might mail me your code without procedures like "border" and so on.

don't try to answer this by "reply " use jotel99(AT)uni.de  instead to contact me
directly.

i know, this is not ng policy, and i won't do your homework at all, but i'll try to give you some hints.

you really should use links given to you some postings ago to learn more about fileIO, pointers, lists and trees (you will have to handle them in a few weeks i guess).

regards
jochen

Re:still having probs with linked list


Quote
Heero Yuy <blade16...@canada.com> wrote:
> I am having problems trying to implement a linked list into my program. I
> have written several procedures that are suppose to sort a linked list while
> I'm entering info. problem is I keep getting an error, and I can't seem to
> figure out how to fix it. Number 1 thing for me is to get the program to

It would be helpful if you said what the error was and where it was
occurring. The more information we have, the easier it is to track down
problems.

Quote
> file when I'm done. Also, how do I delete a node that's pointing to a
> record?

With dispose(). You need to check whether you're disposing the head of the
list, in which case you need to alter the list pointer to point to
node^.next (*before* you dispose node); otherwise, it's simply a matter of
setting previousnode^.next := node^.next and then dispose(node).

Another comment: if you're sure your problem is with the linked-list
aspects, you don't need to post the parts of your program that don't relate
to that, such as procedures for drawing borders etc.

Quote
> Procedure findspot(VAR Current, past:bookptr; nametofind:bookfile;)
> {search the link list for the right spot to place nametofind in alphabetical
> order. when the procedure finishes the current pointer will be pointint to
> the node that will come after the new one}
> VAR found:boolean;
> begin
>      found:=false;
>                   while((current<>nil) and (not found)) DO
>                   begin
>                        if nametofind<current^.book then

Firstly, "bookfile" is not a type, it is a global variable of type
"bookfiletype". And "current^.book" doesn't make sense. You can do
current^.bookinv, though, and I suspect this is what you meant. However,
you're still trying to compare incompatible types -- and the < operator
won't recognise either of them.

It seems to me that you ought to be passing "nametofind" in as a string type
and comparing it to current^.bookinv.title or current^.bookinv.AuthorLastName
or whatever you want to sort by.

Also, if you want to search the entire list you will need to set "current"
to the head of the list before calling this routine. And if the routine
returns after the first comparison the value of "past" is undefined.

In procedure recad you have this:
[read data into variable "book"]

Quote
>               insertnode(head,booktitle);{passes head pointer to the name}
>               write(head^.bookfile,book);{Writes all entries to file}

This makes no sense. In particular, the construction head^.bookfile makes no
sense. There are only two fields of head^, and they are bookinv and next. If
you want to write to a file, you should be using your global variable
bookfile, and there is no need to use head at all unless you also want to
write the data into the linked list.

That ought to be enough to keep you going for a while!

--
______________________________________________________________________
     The Scarlet Manuka,      |        Nitpickers' Party motto:
  Pratchett Quoter At Large,  |  "He who guards his lips guards his
 First Prophet of Bonni, is:  |  soul, but he who speaks rashly will
   sa...@maths.uwa.edu.au     |    come to ruin." -- Proverbs 13:3
______________________________|_______________________________________

Re:still having probs with linked list


JRS:  In article <7diT5.18488$sz3.3704...@news1.telusplanet.net> of Fri,
24 Nov 2000 00:01:07 seen in news:comp.lang.pascal.borland, Heero Yuy

Quote
<blade16...@canada.com> wrote:
>I am having problems trying to implement a linked list into my program. I
>have written several procedures that are suppose to sort a linked list while
>I'm entering info. problem is I keep getting an error, and I can't seem to
>for tempvar:= 19 to 68 do
>begin
>gotoxy(tempvar,8);
>write('')
>end;
>              insertnode(head,booktitle);{passes head pointer to the name}
>              write(head^.bookfile,book);                {Writes all entries
>to file}
>              write('Add another record (Y/N)?');
>              readln(response);
>              until (response='N') or (response='n') {Waits for correct
>response

More people may bother to try to read your code if you format it legibly
for News - put a space after punctuation, indent consistently by a small
amount for each unclosed "begin", etc., don't let the newsreader wrap
lines, ... - and if you simplify it by removing parts not germane to the
problem (it is often not necessary to give the I/O parts, for example,
where the problem is with the list-handling (and if the I/O parts are
really needed, so is test data)).

You say that there is an error : you should say whether it is a compile-
time or run-time error, and give both its number and its descriptive
string.

Pretend that you are a potential answerer : what information is
necessary, what is superfluous?

--
? John Stockton, Surrey, UK.  j...@merlyn.demon.co.uk   Turnpike v4.00   MIME. ?
 Web <URL: http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
 Proper 4-line sig. separator is as above, a line exactly "-- " (SonOfRFC1036)
 Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

Re:still having probs with linked list


On Fri, 24 Nov 2000 00:01:07 GMT, "Heero Yuy" <blade16...@canada.com>
wrote:

Quote
>I am having problems trying to implement a linked list into my program. I
>have written several procedures that are suppose to sort a linked list while
>I'm entering info. problem is I keep getting an error, and I can't seem to
>figure out how to fix it. Number 1 thing for me is to get the program to
>run. It's suppose to get input from a user (it's a database type program)
>take all the info, and write it to a binary file. Now the fun part, I am to
>then take the input and sort it in a linked list then save it to the binary
>file when I'm done. Also, how do I delete a node that's pointing to a
>record?
>So if anyone can help me thanks.

Since you are generating the data before adding to the list, I suggest
you use an insertion sort to put the data where they belong by sorting
on the magnitude of the field desired, alphabetic or numerical value.
The following simple demo shows how to do this and also uses
DISPOSE to erase the whole list. It also shows the number of bytes at
various stages of the process.

Program SortStackAsGenerated;
CONST max = 300; {number of nodes, change as desired}
TYPE
ptr = ^stack;
stack = Record
          dat:Integer;
          nxt:ptr;
        End;
VAR
head:ptr;  {always points to first node of list (or NIL)}
ct, n:Integer;
ans:Char;

Procedure SortList(VAR hd:ptr; k:Integer);
{Inserts single node in sorted position in ascending order}
VAR p, q:ptr;
Begin
     NEW(q); {make new node}
     q^.dat := k;
     q^.nxt := NIL;  {last node always points to NIL}

     If hd <> NIL then  {the list already exists}
     Begin
         If q^.dat < hd^.dat then {new head}
         Begin
              q^.nxt := hd;
              hd := q
         End
         Else
         Begin   {insert node or add new last node}
              p := hd;
              While (q^.dat >= p^.nxt^.dat) AND (p^.nxt <> NIL)
                  Do p := p^.nxt;
              q^.nxt := p^.nxt;
              p^.nxt := q;
         End; {nested if}
     End
     Else hd := q;  {because hd = NIL at beginning}
End;

Procedure ShowList(hd:ptr);
Var p:ptr;
Begin
     p := hd;
     While p <> NIL Do
     Begin
          Write(p^.dat:4);
          p := p^.nxt;
     End;
     Writeln;
End;

Procedure DeleteList(hd:ptr);
VAR p:ptr;
Begin
     p := hd;
     While p^.nxt <> NIL Do
     Begin
          hd := p^.nxt;
          Dispose(p);
          p := hd;
     End;
     Dispose(p);   {for last node which points to NIL}
End;

BEGIN
Repeat
     Randomize;
     head := NIL; {to start list}
     Writeln;  Writeln('heap = ', MEMAVAIL, ' bytes at start.');
     Writeln;
     For ct := 1 to max Do
     Begin
          n := Random(1000);
          SortList(head, n);
      End;
      ShowList(head);
      Writeln('After making list, heap = ', MEMAVAIL);
      DeleteList(head);
      Writeln('After deleting list, heap = ', MEMAVAIL);
      Write('   Again (Y/N)? ');  Readln(ans);
Until UpCase(ans) = 'N';
END.

Other Threads