Jim,
    Some time ago a Computer Sci student was working on Linked Lists and
posted some code she needed help with.
> How would such a thing be done with Perl?
Preuse, run, modify and complete this code (it needs a way to remove a
center link, amoung other things.
I don't take credit for this code, it was originally posted as part of a
request for help. I did take this further by extending (in another script)
the ability to link any node to a parent, left child, center child and right
child.
I don't recomend you use this to try to understand C structures (you just
might opt to abandon C altogether ;-) )

#!/usr/bin/perl -w
use strict;
#create list (1)
sub createllist   {
 my $val  = shift;
 my $node = shift;
 if (  !defined ( $node ) ) {
  die 'I need a scalar reference';
 }
 if ( defined ( $$node ) ) {
  die 'You already have a node! ';
 }
 $$node = {
  'data' => $val,
  'next' => undef,
 };
}
# References V Example Linked List (2)
sub addnode {
 my $val = shift;
 my $list  = shift;
 if ( !defined ($list ) ) {
  die 'I need a scalar reference';
 }
 if ( !defined ($$list )) {
  print "Creating list \n";
  createllist ( $val, $list);
  return;
 }
 if ( defined ($$list -> {'next'} )) {
  $list = $$list ->    {'next'};
 }else {
  $$list -> {'next'} = {
        'data' => $val,
  'next' => undef,
  };
  return;
 }
 while ( defined ($list -> {'next'} )) {
  $list = $list -> {'next'};
 }
 $list -> {'next'} = {
  'data' => $val,
  'next'  => undef,
 }
}

# To print the values to be used (3)sub printllist {
 my $list = shift;
    while ( defined ( $list ) ) {
    print $list -> {'data'}, "\n";
    $list = $list -> {'next'};
    }
}

#for debugging, use the  Data::Dumper module:
use Data::Dumper;
my $llist;
addnode (1,\$llist );

print "dump:";
print Dumper ($llist);
addnode (2,\$llist );
addnode (3,\$llist );
addnode (4,\$llist );
printllist ( $llist );

print "dump:";
print Dumper ($llist);




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to