package data_string;
sub new{
shift();
my $val=undef;
my $ref=undef;
($val,$ref)=@_;
my $new_string={
val => $val,
ref => $ref
};
bless $new_string, data_string;
return $new_string;
}
#return a reference to the hash holding two incoming parameters which are value of the node and a #reference to a next node
sub val{
return shift()->{val};
}
#return the value of the node
sub ref{
return shift()->{ref};
}
#return a reference to the following node
sub setval{
my $tnode=shift();
if(@_){
my $tval=shift();
$tnode->{val}=$tval;
return 1;
}
return 0;
}
#set the node with a new value
sub setref{
my $tnode=shift();
my $tref=shift();
if(CORE::ref($tnode)){
$tnode->{ref}=$tref;
return 1;
}
return 0;
}
#set the node with a new reference
sub setnull{
undef %{shift()};
return 1;
}
#undefine the node
sub length{
my $count=0;
my $head=shift();
while( defined($head) ){ $count++; $head=$head->ref;}
return $count;
}
#return the length of a list whose head is the current node
sub insert{
my $head=shift();
my $pos=undef;
my $str=undef;
if(@_==2){
($pos, $str)=@_;
if($pos>=$head->length && $pos<0)
{return 0;}
else
{
my $pre=$head;
my $cur=$pre->ref;
my $index=0;
while($index!=$pos && defined($cur)){
$pre=$cur;
$cur=$cur->ref;
$index++;
}#while
$pre->setref(data_string->new($str, $cur));
return 1;
}#else
}
return 0;
}
#insert the current node leading list a new node taking the incoming parameter as the value
sub delete{
if($_[1]==0){
if($_[0]->length==1){shift()->setnull; return 1;}
else{
my $fir=shift;
my $sec=$fir->ref;
$fir->setval($sec->val);
$fir->setref($sec->ref);
$sec->setnull;
return 1;
}
}
my $head=shift();
if(@_){
my $pos=shift();
if($pos>=$head->length && $pos<=0)
{return 0;}#if
else{
my $pre=$head;
my $cur=$pre->ref;
my $index=1;
while($index<$pos){
$pre=$cur;
if(defined($cur)){$cur=$cur->ref;}
$index++;
}#while
$pre->setref($cur->ref);
$cur->setnull;
return 1;
}#else
}#if
return 0;
}
#delete the current node leading list a node whose position is related to the incoming parameter
1;
#写了个测试程序:
use data_string;
$temp=undef;
$node=data_string->new(1, $temp);
foreach (qw(2 3 4 5)){
$ind=$_-2;
if($ind<$node->length){
$node->insert($ind, $_);
}
}
$node->delete(3);
$temp=$node;
while(defined($temp)){
print($temp->val."\n");
$temp=$temp->ref;
}