forked from manwar/perlweeklychallenge-club
/
ch-2.pl
executable file
·82 lines (62 loc) · 1.32 KB
/
ch-2.pl
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
#!/usr/bin/perl
package Node;
use Moo;
use namespace::autoclean;
has _value => (
is => 'rw',
);
has _next => (
is => 'rw',
isa => sub { return ref eq 'Node'; },
);
sub BUILDARGS {
my ($orig, $class, @args) = @_;
return { _value => $args[0], _next => undef };
}
sub add {
my ($self, $newval) = @_;
my $v = $self;
while ($v->{_next}) {
$v = $v->{_next};
}
$v->{_next} = Node->new(value => $newval);
}
sub print {
my ($self) = @_;
my $v = $self;
while ($v) {
print $v->{_value} // q{}, q{ };
$v = $v->{_next};
}
print "\n";
}
sub reorder() {
my ($self) = @_;
my $current = $self;
while ($current) {
my $last = $current;
my $second = $current;
while ($last->{_next}) {
$second = $last;
$last = $last->{_next};
}
$second->{_next} = undef;
$last->{_next} = $current->{_next};
$current->{_next} = $last;
if ($current->{_next}) {
$current = $current->{_next}->{_next};
} else {
$current = $current->{_next};
}
}
}
1;
package main;
use 5.020;
use warnings;
my $linked_list = Node->new(value => 1);
$linked_list->add(2);
$linked_list->add(3);
$linked_list->add(4);
$linked_list->reorder();
$linked_list->print();