aboutsummaryrefslogtreecommitdiff
path: root/challenge-095/colin-crain/perl/ch-2.pl
blob: 3884e8b26dd942c30ee4513e8da463038deb55b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#! /opt/local/bin/perl
#
#       jenga.pl
#
#         TASK #2 › Demo Stack
#         Submitted by: Mohammad S Anwar
#         Write a script to demonstrate Stack operations like below:
#
#             push($n) - add $n to the stack
#             pop() - remove the top element
#             top() - get the top element
#             min() - return the minimum element
#
#         Example:
#
#             my $stack = Stack->new;
#             $stack->push(2);
#             $stack->push(-1);
#             $stack->push(0);
#             $stack->pop;       # removes 0
#             print $stack->top; # prints -1
#             $stack->push(0);
#             print $stack->min; # prints -1
#
#
#       © 2021 colin crain
#
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##



use warnings;
use strict;
use feature ":5.26";


package Node;
use Moo;

    has value => ( is => 'rw' );
    has down  => ( is => 'rw' );

package Stack;
use Moo;

    has last => ( is => 'rw' );

    sub push {
        my ($self, $value) = @_;
        my $node = Node->new( value => $value ,
                              down  => $self->last  );
        $self->last( $node );
    };

    sub pop {
        my $self = shift;
        my $node = $self->last;
        $self->last( $node->down );
        return $node->value;
    }

    sub top {
        my $self = shift;
       return $self->last->value;
    }

    sub min {
        my $self = shift;
        my $node = $self->last;
        my $min  = $node->value;
        while ( defined $node->down ) {
            $min = $node->down->value if $node->down->value < $min;
            $node = $node->down;
        }
        return $min;
    }

package main;

my $stack = Stack->new;
$stack->push( 2 );
$stack->push( -1 );
$stack->push( 0 );
$stack->pop;                # removes 0
say $stack->top;            # prints -1
$stack->push( 0 );
say $stack->min;            # prints -1