blob: cf703da48d85cb879676a4289466f421c6171694 (
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
|
#! /usr/bin/env raku
subset PosInt of Int where * >= 1;
unit sub MAIN (PosInt $N, :$v, :$verbose = :$v, :$limit = 50);
class LinkedElement
{
has $.value is rw;
has $.next is rw;
method print-list
{
print self.value;
if self.next
{
print " -> ";
self.next.print-list;
}
else
{
print "\n";
}
}
method list-length
{
my $length = 1;
my $current = self.next;
while ($current)
{
$current = $current.next;
$length++;
}
return $length;
}
}
my $length = (1..$limit).pick;
my $head;
my $current;
for 1..$length -> $value
{
my $new = LinkedElement.new(value => $value);
if $current
{
$current.next = $new;
$current = $current.next;
}
else # Initially
{
$head = $new;
$current = $head;
}
}
$head.print-list;
say "Length: ", $head.list-length if $verbose;
remove-element($head, $N);
$head
?? $head.print-list
!! say "[]";
sub remove-element ($list is rw, $from-the-end)
{
my $length = $list.list-length;
if $from-the-end > $length
{
$list = $list.next;
}
else
{
my $current = $list;
for 1 .. ($length - $from-the-end -1)
{
$current = $current.next;
}
$current.next = $current.next.next;
}
}
|