23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Some Observations about the CircleList Class<br />

There are a few observations we can make about the CircleList class. It is a<br />

simple program that can provide enough functionality to simulate circle games,<br />

like Duck, Duck, Goose, as we will soon show. It is not a robust program,<br />

however. In particular, if a circle list is empty, then call<strong>in</strong>g advance or remove<br />

on that list will cause an exception. (Which one?) Exercise R-3.5 deals with this<br />

exception-generat<strong>in</strong>g behavior <strong>and</strong> ways of h<strong>and</strong>l<strong>in</strong>g this empty-list condition<br />

better.<br />

Duck, Duck, Goose<br />

In the children's game, Duck, Duck, Goose, a group of children sit <strong>in</strong> a circle. One<br />

of them is elected "it" <strong>and</strong> that person walks around the outside of the circle. The<br />

person who is "it" pats each child on the head, say<strong>in</strong>g "Duck" each time, until<br />

reach<strong>in</strong>g a child that the "it" person identifies as "Goose." At this po<strong>in</strong>t there is a<br />

mad scramble, as the "Goose" <strong>and</strong> the "it" person race around the circle. Who<br />

ever returns to the Goose's former place first gets to rema<strong>in</strong> <strong>in</strong> the circle. The loser<br />

of this race is the "it" person for the next round of play. This game cont<strong>in</strong>ues like<br />

this until the children get bored or an adult tells them it is snack time, at which<br />

po<strong>in</strong>t the game ends. (See Figure 3.19.)<br />

Figure 3.19: The Duck, Duck, Goose game: (a)<br />

choos<strong>in</strong>g the "Goose;" (b) the race to the "Goose's"<br />

place between the "Goose" <strong>and</strong> the "it" person.<br />

Simulat<strong>in</strong>g this game is an ideal application of a circularly l<strong>in</strong>ked list. The<br />

children can represent nodes <strong>in</strong> the list. The "it" person can be identified as the<br />

person sitt<strong>in</strong>g after the cursor, <strong>and</strong> can be removed from the circle to simulate the<br />

march<strong>in</strong>g around. We can advance the cursor with each "Duck" the "it" person<br />

identifies, which we can simulate with a r<strong>and</strong>om decision. Once a "Goose" is<br />

183

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!