自定义简易的面向对象的perl栈与队列类

         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(),"\n";
$stack->pop();
print $stack->toString(),"\n";
$stack->pop();
print $stack->toString(),"\n";
$stack->pop();
print $stack->toString(),"\n";


use Queue;
$queue=Queue->new();
$queue->en_queue(1);
$queue->en_queue('a');
$queue->en_queue('2');
print $queue->toString(),"\n";
$queue->de_queue();
print $queue->toString();

 以上Stack与Queue只是个简单实现,其他操作未添加

你可能感兴趣的:(perl)