aboutsummaryrefslogtreecommitdiff
path: root/challenge-068/mohammad-anwar/perl/ch-2.pl
blob: a49ca3bf8d419d68e1271ae60b18a2e01f1b7ad2 (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
#!/usr/bin/perl

#
# Perl Weekly Challenge - 068
#
# Task #2: Reorder List
#
# https://perlweeklychallenge.org/blog/perl-weekly-challenge-068/
#

package Node;

use Moo;

has v => (is => 'rw');
has c => (is => 'rw');

sub show_link {
    my ($self) = @_;

    my $head = $self;
    my @v = ();
    while ($head->c) {
        push @v, $head->v;
        $head = $head->c;
    }
    push @v, $head->v;

    return sprintf("%s", join ' -> ', @v);
}

package main;

my $list = $ARGV[0]//'1 -> 2 -> 3 -> 4 -> 5';
print reorder_list($list)->show_link, "\n";

#
#
# METHODS

sub reorder_list {
    my ($list) = @_;

    $list =~ s/\s+//g;
    $list = [ split /\-\>/, $list ];
    my $head = Node->new(v => shift @$list);
    my $link = [ $head ];

    # prepare singly linked list
    foreach my $v (@$list) {
        my $node = Node->new(v => $v);
        $link->[-1]->c($node);
        push @$link, $node;
    }

    # reorder linked list
    my $i = 1;
    foreach (0 .. int($#$list/2)) {
        my $node = pop @$link;
        splice(@$link, $i, 0, $node);

        # remove child from the last node
        $link->[-1]->c(undef);

        # link new node to previous node
        $link->[$i-1]->c($node);

        # make the next node as child of new node
        $node->c($link->[$i+1]);

        $i += 2;
    }

    return $head;
}