044_quiz5.zig 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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");
  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. std.debug.print("\n", .{});
  28. }
  29. // This function visits all elephants once, starting with the
  30. // first elephant and following the tails to the next elephant.
  31. // If we did not "mark" the elephants as visited (by setting
  32. // visited=true), then this would loop infinitely!
  33. fn visitElephants(first_elephant: *Elephant) void {
  34. var e = first_elephant;
  35. while (!e.visited) {
  36. std.debug.print("Elephant {u}. ", .{e.letter});
  37. e.visited = true;
  38. e = e.tail;
  39. }
  40. }