perl中的数组其实已经具备了栈与队列的特点,下面是对数组经过一些封装的stack,queue对象
1、Stack类
创建一个Stack.pm文件
package Stack; sub new{ $self={ arr=>[] }; return bless $self; } sub push{ $self=shift; $d=shift; push @{$self->{arr}},$d; } sub pop{ $self=shift; return pop @{$self->{arr}}; } sub toString{ $self=shift; return @{$self->{arr}}; } 1;
2、Queue类
创建一个Queue.pm
package Queue; sub new{ $self={ arr=>[] }; return bless $self; } sub en_queue{ $self=shift; $d=shift; push @{$self->{arr}},$d; } sub de_queue{ $self=shift; return shift @{$self->{arr}}; } sub toString{ $self=shift; return @{$self->{arr}}; } 1;
3、调用
use Stack; $stack=new Stack; $stack->push('gg'); $stack->push('aa'); $stack->push('123'); print $stack->toString()," "; $stack->pop(); print $stack->toString()," "; $stack->pop(); print $stack->toString()," "; $stack->pop(); print $stack->toString()," "; use Queue; $queue=Queue->new(); $queue->en_queue(1); $queue->en_queue('a'); $queue->en_queue('2'); print $queue->toString()," "; $queue->de_queue(); print $queue->toString();
参考的链接
https://www.lagou.com/lgeduarticle/9240.html