As promised yesterday, this is my code to create a linked list and count its nodes:
use strict;
use warnings;
use Data::Dumper;
my $pt = { value => "D", next => undef };
my $pt2 = {value => "C", next => $pt};
$pt = {value => "B", next => $pt2};
my $L = { value => "A", next => $pt};
sub solution {
my $list = shift;
my $length = 0;
while (1) {
return $length unless defined $list->{value}; # added for the
+case of an empty list
print $list->{value};
$length++;
return $length unless defined $list->{next};
$list = $list->{next};
}
}
my $len = solution($L);
print "\n$len \n";
print Dumper $L;
Which finds 4 nodes and prints this:
ABCD
4
$VAR1 = {
'next' => {
'next' => {
'next' => {
'next' => undef,
'value' => 'D'
},
'value' => 'C'
},
'value' => 'B'
},
'value' => 'A'
};
As I said yesterday, the initialization of the list could be simpler, but perhaps less easy to understand for a relative beginner. But this is how I would probably code the initialization of the linked list:
my $L = {
value => "A", next => {
value => "B", next => {
value => "C", next => {
value => "D", next => undef,
}
}
}
};
Or, better (especially if there are more nodes), I would construct it in a loop:
my $L;
for ( reverse qw / A B C D E F G/) {
my $pt = { value => $_, next => $L };
$L = $pt;
}
Which prints:
$ perl linked_list.pl
ABCDEFG
7
$VAR1 = {
'next' => {
'next' => {
'next' => {
'next' => {
'next' => {
+'next' => {
+ 'next' => undef,
+ 'value' => 'G'
+ },
+'value' => 'F'
},
'value' => '
+E'
},
'value' => 'D'
},
'value' => 'C'
},
'value' => 'B'
},
'value' => 'A'
};