diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-02-09 20:15:09 -0500 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-02-09 20:15:45 -0500 |
commit | 961cf22b88021e9c62d83bd840fe54f205c45f5f (patch) | |
tree | 9503434d0f4e417293527b0e5f3a8dc84ab00bd8 /exercises/44_quiz5.zig | |
parent | 55ad7c32f2d534b1fbd438204d21738f958c51a5 (diff) | |
download | ziglings-961cf22b88021e9c62d83bd840fe54f205c45f5f.tar.gz ziglings-961cf22b88021e9c62d83bd840fe54f205c45f5f.tar.bz2 ziglings-961cf22b88021e9c62d83bd840fe54f205c45f5f.tar.xz ziglings-961cf22b88021e9c62d83bd840fe54f205c45f5f.zip |
Added Quiz 5 for pointers. Elephants!!!
Diffstat (limited to 'exercises/44_quiz5.zig')
-rw-r--r-- | exercises/44_quiz5.zig | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/exercises/44_quiz5.zig b/exercises/44_quiz5.zig new file mode 100644 index 0000000..6ec0da9 --- /dev/null +++ b/exercises/44_quiz5.zig @@ -0,0 +1,45 @@ +// +// "Elephants walking +// Along the trails +// +// Are holding hands +// By holding tails." +// +// from Holding Hands +// by Lenore M. Link +// +const std = @import("std"); // single quotes + +const Elephant = struct{ + letter: u8, + tail: *Elephant = undefined, + visited: bool = false, +}; + +pub fn main() void { + var elephantA = Elephant{ .letter = 'A' }; + // (Please add Elephant B here!) + var elephantC = Elephant{ .letter = 'C' }; + + // Link the elephants so that each tail "points" to the next elephant. + // They make a circle: A->B->C->A... + elephantA.tail = &elephantB; + // (Please link Elephant B's tail to Elephant C here!) + elephantC.tail = &elephantA; + + visitElephants(&elephantA); +} + +// This function visits all elephants once, starting with the +// first elephant and following the tails to the next elephant. +// If we did not "mark" the elephants as visited (by setting +// visited=true), then this would loop infinitely! +fn visitElephants(first_elephant: *Elephant) void { + var e = first_elephant; + + while (!e.visited) { + std.debug.print("Elephant {u}. ", .{e.letter}); + e.visited = true; + e = e.tail; + } +} |