summaryrefslogtreecommitdiff
path: root/linked-list-demo.pl
blob: 069cb3c78da47fd30ee1f7c6bfa0582d46e97ae9 (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
#!/usr/bin/env perl

use strict;
use warnings;
use utf8;

use 5.006;

# Two pointers: one to the head of the list, one to the "current" node
my $head = undef;
my $cur  = undef;

### Build the list:

# Read lines of text, and add a new node to the list each time
while ( defined( my $line = <> ) ) {

    # Make a new node: a hashref with two fields; one with our read line, and
    # one pointing to the "next" node, and there isn't one yet, so we'll make
    # that undef
    my $new = {
        line => $line,
        next => undef,
    };

    # If $head doesn't yet point anywhere, this is the first node in our list,
    # so Make that our starting point
    if ( not defined $head ) {
        $head = $new;
    }

    # Otherwise, we make the new node the "next" one of the last one we created
    else {
        $cur->{next} = $new;
    }

    # The node we just created then becomes our "current" node.
    $cur = $new;
}

### Print the list:

# Starting at $head, print the node's text and follow its "next" until it's
# "undef", i.e. we've reached the end of the chain.
print "Pre-insert:\n";
for ( $cur = $head ; defined $cur ; $cur = $cur->{next} ) {
    print "\t$cur->{line}";
}

### Insert into the list:

# Add a node with string "lmao" after any node with string "ayy"
for ( $cur = $head ; defined $cur ; $cur = $cur->{next} ) {

    # Just keep walking if we don't match
    next if $cur->{line} ne "ayy\n";

    # Make a new node, and make its next node whatever the current node's
    # "next" was going to be; we're stealing its link, inserting it into the
    # chain.
    my $new = {
        line => "lmao\n",
        next => $cur->{next},
    };

    # Re-point the current node's "next" to the node we just created.
    $cur->{next} = $new;
}

### Print the list again:
print "Post-insert:\n";
for ( $cur = $head ; defined $cur ; $cur = $cur->{next} ) {
    print "\t$cur->{line}";
}