in reply to Doubly link list implementation
This was a useful exercise in Pascal or C to learn how to use pointers. Helped with conceptualizing them, and also taught a thing or three about how to turn a description into an algorithm, handling end cases and always being aware of the actual contents of a variable, which are useful in programming in general.
But if I really need to keep track of what proceeds and what follows, I choose to avoid references/pointers as needlessly complex.
use strict; use warnings; my @list; # Creating a doubly linked list while (<DATA>){ push @list, $_ } chomp @list; &print_list(); sub print_list { my $format = "%5s -> %5s -> %5s\n"; printf $format,'prev','data','next'; for (my $i=0; $i<$#list; $i++) { printf $format, $i>0 ? $list[$i-1] : 'undef', $list[$i], $i < $#list - 1 ? $list[$i+1] : 'undef' } } __DATA__ the quick brown fox jumps over the lazy dog
Output:
prev -> data -> next undef -> the -> quick the -> quick -> brown quick -> brown -> fox brown -> fox -> jumps fox -> jumps -> over jumps -> over -> the over -> the -> lazy the -> lazy -> dog lazy -> dog -> undef
|
|---|