gyn

Win32下的Perl,无用的select,停滞的Tk,结束吧....

perl编程:一个链表类

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;
}

r_data_string.jpg

posted on 2006-04-29 19:21 gyn_tadao 阅读(941) 评论(0)  编辑 收藏 引用 所属分类: perl

只有注册用户登录后才能发表评论。
<2006年4月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

导航

统计

常用链接

留言簿(15)

随笔分类(126)

随笔档案(108)

相册

搜索

最新评论

阅读排行榜

评论排行榜