This program does something like this well known animation (click to see it in action)
See also
Click to enlarge diagram
package twisted.loops; /* * Builds a mobius loop (a circular linked list). The loop is * composed of several segments ("strips"). Each strip has two * "sides." The "top" of a strip is attached top of the next, * the "bottom" to the next's bottom. The last such attachment * is "twisted" (top to bottom, bottom to top) so the loop has, * effectively, only one side. */ public class Mobius { public static void main(String[] args) { Mobius mobius = new Mobius(); Strip strip = mobius.create(); Fly fly = mobius.new Fly(); fly.land(strip.top); fly.escape(); } /* * A loop segment with "two" sides */ class Strip { Side top; Side bottom; String id; Strip(String id) { this.id = id; top = new Side(id + "-top"); bottom = new Side(id + "-bottom"); } public String toString() { return "Strip: " + id + ", " + ", top=" + top + ", bottom=" + bottom; } // Insert new strip/segment to loop Strip attach(Strip strip) { // We point to new strip. New // strip points to next strip swap(top.next, strip.top.next); swap(bottom.next, strip.bottom.next); return this; } void swap(Side a, Side b) { Side temp = a.next; a.next = b.next; b.next = temp; } // Twist a strip's connection to the next strip in the list. // Its "top" will point to the next one's "bottom" // and its "bottom" will point to the next one's "top" Strip twist() { Side temp = top.next; top.next = bottom.next; bottom.next = temp; return this; } } /* * One "side" of a strip (loop segment) */ class Side { String id; Side next; public Side(String id) { this.id = id; next = this; } public String toString() { return "Side=" + id; } Side trap(Fly fly) { fly.land(this); return this; } } class Fly { Side legs; public Fly land(Side side) { legs = side; return this; } void crawl() { legs = legs.next; } void escape() { for (int count = 0; count < 25; count++) { System.out.println(this); crawl(); } } public String toString() { return "Fly legs=" + legs; } } /* * Build a mobius loop (a circular linked list) * Uses method "chaining," see * http://en.wikipedia.org/wiki/Method_chaining */ Strip create() { Strip strip = new Strip("A") .attach(new Strip("B")) .attach(new Strip("C")) .attach(new Strip("D")); strip.twist(); return strip; } /* * Simple infinite loop */ static void loop(int n) { for (int i=0; i < n; i = (i+1)%n) { System.out.println(i); } } }