in reply to Perl linked list
Which finds 4 nodes and prints this: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;
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:ABCD 4 $VAR1 = { 'next' => { 'next' => { 'next' => { 'next' => undef, 'value' => 'D' }, 'value' => 'C' }, 'value' => 'B' }, 'value' => 'A' };
Or, better (especially if there are more nodes), I would construct it in a loop:my $L = { value => "A", next => { value => "B", next => { value => "C", next => { value => "D", next => undef, } } } };
Which prints: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' };
|
|---|