Chinaunix首页 | 论坛 | 博客
  • 博客访问: 131264
  • 博文数量: 36
  • 博客积分: 155
  • 博客等级: 入伍新兵
  • 技术积分: 282
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-27 20:57
文章分类

全部博文(36)

文章存档

2014年(1)

2013年(21)

2012年(15)

分类: PERL

2013-04-22 15:36:01

简单实现了一下链表,待后续使用时再丰富。

  1. #!/usr/bin/perl -w
  2. use strict;
  3. use Data::Dumper;

  4. package LinkNode;
  5. use Moose;

  6. has 'next' => (
  7.     is => 'rw',
  8.     isa => 'LinkNode',
  9.     builder => '_build_node',
  10.     lazy => 1, # 使得next只有在read时被创建,这就防止了循环创建下去的问题
  11.     predicate => 'has_next',
  12.     clearer => 'clear_next',
  13. );

  14. has 'data' => (
  15.     is => 'rw',
  16.     isa => 'Any',
  17.     predicate => 'has_data',
  18.     clearer => 'clear_data',
  19. );

  20. sub _build_node {
  21.     return LinkNode->new();
  22. }

  23. sub has_node {
  24.     my $self = shift;
  25.     return $self->has_next || $self->has_data;
  26. }

  27. sub clear_node {
  28.     my $self = shift;
  29.     $self->clear_next;
  30.     $self->clear_data;
  31.     return;
  32. }

  33. package LinkList;
  34. use Moose;
  35. extends 'LinkNode';

  36. has 'head' => (
  37.     is => 'rw',
  38.     isa => 'LinkNode',
  39.     builder => '_build_node',
  40.     lazy => 1,
  41. );

  42. has 'tail' => (
  43.     is => 'rw',
  44.     isa => 'LinkNode',
  45.     builder => '_build_node',
  46.     lazy => 1,
  47. );

  48. sub insert {
  49.     my $self = shift;
  50.     my $item = shift;
  51.     my $node = LinkNode->new( data => $item );
  52.     $node->next($self->head);
  53.     $self->head($node);
  54.     $self->tail($node) if not $self->tail->has_node;
  55.     return;
  56. }

  57. sub append {
  58.     my $self = shift;
  59.     my $item = shift;
  60.     my $node = LinkNode->new( data => $item );
  61.     if ( not $self->tail->has_node ) {
  62.         $self->head($node);
  63.         $self->tail($node);
  64.     } else {
  65.         $self->tail->next($node);
  66.         $self->tail($node);
  67.     }
  68.     return;
  69. }

  70. sub get {
  71.     my $self = shift;
  72.     return if not $self->head->has_node;
  73.     my $next = $self->head->next;
  74.     my $data = $self->head->data;
  75.     if ( not $next->has_data ) {
  76.         $self->head->clear_node;
  77.         $self->tail->clear_node;
  78.     } else {
  79.         $self->head($next);
  80.     }
  81.     return $data;
  82. }

  83. package main;

  84. my $link = LinkList->new();
  85. for ( 1 .. 3 ) {
  86.     $link->append($_);
  87. }
  88. for ( 4 .. 6 ) {
  89.     $link->insert($_);
  90. }
  91. print Dumper $link;

  92. my $data;
  93. for ( 1 .. 7 ) {
  94.     $data = $link->get();
  95.     print defined $data ? "I get: $data\n" : "I can't get\n";
  96.     #print Dumper $link;
  97. }
  98. exit;





阅读(1708) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~