044_quiz5.zig 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 elephantB = Elephant{ .letter = 'B' };
  21. var elephantC = Elephant{ .letter = 'C' };
  22. // Link the elephants so that each tail "points" to the next elephant.
  23. // They make a circle: A->B->C->A...
  24. elephantA.tail = &elephantB;
  25. // (Please link Elephant B's tail to Elephant C here!)
  26. elephantB.tail = &elephantC;
  27. elephantC.tail = &elephantA;
  28. visitElephants(&elephantA);
  29. std.debug.print("\n", .{});
  30. }
  31. // This function visits all elephants once, starting with the
  32. // first elephant and following the tails to the next elephant.
  33. // If we did not "mark" the elephants as visited (by setting
  34. // visited=true), then this would loop infinitely!
  35. fn visitElephants(first_elephant: *Elephant) void{
  36. var e = first_elephant;
  37. while(!e.visited){
  38. std.debug.print("Elephant {u}. ", .{e.letter});
  39. e.visited = true;
  40. e = e.tail;
  41. }
  42. }