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;
####
ABCD
4
$VAR1 = {
'next' => {
'next' => {
'next' => {
'next' => undef,
'value' => 'D'
},
'value' => 'C'
},
'value' => 'B'
},
'value' => 'A'
};
####
my $L = {
value => "A", next => {
value => "B", next => {
value => "C", next => {
value => "D", next => undef,
}
}
}
};
####
my $L;
for ( reverse qw / A B C D E F G/) {
my $pt = { value => $_, next => $L };
$L = $pt;
}
####
$ 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'
};