summaryrefslogtreecommitdiff
path: root/linked-list-demo.pl
diff options
context:
space:
mode:
Diffstat (limited to 'linked-list-demo.pl')
-rw-r--r--linked-list-demo.pl74
1 files changed, 74 insertions, 0 deletions
diff --git a/linked-list-demo.pl b/linked-list-demo.pl
new file mode 100644
index 0000000..069cb3c
--- /dev/null
+++ b/linked-list-demo.pl
@@ -0,0 +1,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}";
+}