简单实现了一下链表,待后续使用时再丰富。
-
#!/usr/bin/perl -w
-
use strict;
-
use Data::Dumper;
-
-
package LinkNode;
-
use Moose;
-
-
has 'next' => (
-
is => 'rw',
-
isa => 'LinkNode',
-
builder => '_build_node',
-
lazy => 1, # 使得next只有在read时被创建,这就防止了循环创建下去的问题
-
predicate => 'has_next',
-
clearer => 'clear_next',
-
);
-
-
has 'data' => (
-
is => 'rw',
-
isa => 'Any',
-
predicate => 'has_data',
-
clearer => 'clear_data',
-
);
-
-
sub _build_node {
-
return LinkNode->new();
-
}
-
-
sub has_node {
-
my $self = shift;
-
return $self->has_next || $self->has_data;
-
}
-
-
sub clear_node {
-
my $self = shift;
-
$self->clear_next;
-
$self->clear_data;
-
return;
-
}
-
-
package LinkList;
-
use Moose;
-
extends 'LinkNode';
-
-
has 'head' => (
-
is => 'rw',
-
isa => 'LinkNode',
-
builder => '_build_node',
-
lazy => 1,
-
);
-
-
has 'tail' => (
-
is => 'rw',
-
isa => 'LinkNode',
-
builder => '_build_node',
-
lazy => 1,
-
);
-
-
sub insert {
-
my $self = shift;
-
my $item = shift;
-
my $node = LinkNode->new( data => $item );
-
$node->next($self->head);
-
$self->head($node);
-
$self->tail($node) if not $self->tail->has_node;
-
return;
-
}
-
-
sub append {
-
my $self = shift;
-
my $item = shift;
-
my $node = LinkNode->new( data => $item );
-
if ( not $self->tail->has_node ) {
-
$self->head($node);
-
$self->tail($node);
-
} else {
-
$self->tail->next($node);
-
$self->tail($node);
-
}
-
return;
-
}
-
-
sub get {
-
my $self = shift;
-
return if not $self->head->has_node;
-
my $next = $self->head->next;
-
my $data = $self->head->data;
-
if ( not $next->has_data ) {
-
$self->head->clear_node;
-
$self->tail->clear_node;
-
} else {
-
$self->head($next);
-
}
-
return $data;
-
}
-
-
package main;
-
-
my $link = LinkList->new();
-
for ( 1 .. 3 ) {
-
$link->append($_);
-
}
-
for ( 4 .. 6 ) {
-
$link->insert($_);
-
}
-
print Dumper $link;
-
-
my $data;
-
for ( 1 .. 7 ) {
-
$data = $link->get();
-
print defined $data ? "I get: $data\n" : "I can't get\n";
-
#print Dumper $link;
-
}
-
exit;
阅读(1714) | 评论(0) | 转发(0) |