sub insert_after {
my ($previous, $val) = @_;
my $curr_next = $previous->{next};
$previous->{next} = {
"data" => $val ,
"next" => $curr_next,
"prev" => $previous,
};
my $new_next = $previous->{next};
$curr_next->{prev} = $new_next if defined $curr_next;
return $new_next;
}
sub insert_before {
# simply call insert_after on the previous node
my ($previous, $val) = @_;
return insert_after($previous->{prev}, $val);
}
####
sub display {
my $curr = shift;
while (1) {
last unless defined $curr->{next};
print "Current: ", $curr->{data},
"\tPrevious: ", $curr->{prev}{data} // "",
"\tNext: ", $curr->{next}{data} // "", "\n";
$curr = $curr->{next};
}
print "\n";
}
####
my $head = {data => 0, prev => undef, next => undef};
my $previous = $head;
while (){
# ... same as in previous post
}
display($head);
my $new_node = insert_after ($head, 0.5);
$new_node = insert_before ($new_node->{next}, 0.7);
display($head);
####
$ perl doubly_linked.pl
Current: 0 Previous: Next: 1
Current: 1 Previous: 0 Next: 2
Current: 2 Previous: 1 Next: 3
Current: 3 Previous: 2 Next: 4
Current: 4 Previous: 3 Next: 5
Current: 0 Previous: Next: 0.5
Current: 0.5 Previous: 0 Next: 0.7
Current: 0.7 Previous: 0.5 Next: 1
Current: 1 Previous: 0.7 Next: 2
Current: 2 Previous: 1 Next: 3
Current: 3 Previous: 2 Next: 4
Current: 4 Previous: 3 Next: 5
####
my $head = {data => 0, prev => undef, next => undef};
my $tail = $head;
while (){
chomp;
$tail = insert_after($tail, $_);
}
####
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $head = {data => 0, prev => undef, next => undef};
my $tail = $head;
while (){
chomp;
$tail = insert_after($tail, $_); # new tail returned each time through
}
display($head);
my $new_node = insert_after ($head, 0.5);
$new_node = insert_before ($new_node->{next}, 0.7);
# adding a new node before the tail
$new_node = insert_before ($tail, 4.5);
display($head);
####
$ perl doubly_linked.pl
Current: 0 Previous: Next: 1
Current: 1 Previous: 0 Next: 2
Current: 2 Previous: 1 Next: 3
Current: 3 Previous: 2 Next: 4
Current: 4 Previous: 3 Next: 5
Current: 0 Previous: Next: 0.5
Current: 0.5 Previous: 0 Next: 0.7
Current: 0.7 Previous: 0.5 Next: 1
Current: 1 Previous: 0.7 Next: 2
Current: 2 Previous: 1 Next: 3
Current: 3 Previous: 2 Next: 4
Current: 4 Previous: 3 Next: 4.5
Current: 4.5 Previous: 4 Next: 5