44_quiz5.zig 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // "Elephants walking
  3. // Along the trails
  4. //
  5. // Are holding hands
  6. // By holding tails."
  7. //
  8. // from Holding Hands
  9. // by Lenore M. Link
  10. //
  11. const std = @import("std"); // single quotes
  12. const Elephant = struct {
  13. letter: u8,
  14. tail: *Elephant = undefined,
  15. visited: bool = false,
  16. };
  17. pub fn main() void {
  18. var elephantA = Elephant{ .letter = 'A' };
  19. // (Please add Elephant B here!)
  20. var elephantC = Elephant{ .letter = 'C' };
  21. // Link the elephants so that each tail "points" to the next elephant.
  22. // They make a circle: A->B->C->A...
  23. elephantA.tail = &elephantB;
  24. // (Please link Elephant B's tail to Elephant C here!)
  25. elephantC.tail = &elephantA;
  26. visitElephants(&elephantA);
  27. }
  28. // This function visits all elephants once, starting with the
  29. // first elephant and following the tails to the next elephant.
  30. // If we did not "mark" the elephants as visited (by setting
  31. // visited=true), then this would loop infinitely!
  32. fn visitElephants(first_elephant: *Elephant) void {
  33. var e = first_elephant;
  34. while (!e.visited) {
  35. std.debug.print("Elephant {u}. ", .{e.letter});
  36. e.visited = true;
  37. e = e.tail;
  38. }
  39. }