#!/usr/bin/perl
use strict;
use warnings;
use constant NEXT => 0;
use constant VAL => 1;
my ($list, $tail);
my($pred, $temp);
$list = $tail = undef;
# insertion. A linked queue.
foreach (1 .. 5) {
my $node = [undef, $_ * $_];
if(not defined $tail) {
$list = $tail = $node;
} else {
$tail->[NEXT] = $node;
$tail = $node;
}
}
$temp = $list;
# print the values in the list.
while (defined $temp) {
print $temp->[VAL], "\n";
$temp = $temp->[NEXT];
}
# deletion
print "Enter element to be destroyed\n";
my $ele = <>;
chomp $ele;
$pred = $list;
$temp = $list->[NEXT];
while (defined $temp) {
if($temp->[VAL] == $ele) {
$pred->[NEXT] = $temp->[NEXT];
print "$temp->[VAL] found!\n";
$temp->[NEXT] = undef;
last;
} else {
$temp = $temp->[NEXT];
}
}
print "list after deleting $ele\n";
while (defined $list) {
print $list->[VAL], "\n";
$list = $list->[NEXT];
}
####
1
4
9
16
25
####
1
25