The prisoners can ensure freedom for all prisoners except the very first
one (the one at the back of the line).
The first prisoner should say "white" if he sees an odd number of white hats
in front of him, or "black" if he sees an even number of white hats. The
prisoner just in front of him sees the exact same set of hats with the
exception of his own. Thus, the parity of the number of white hats he sees
is the same as indicated by the prisoner behind him, he knows that his hat
must be black. Therefore, this prisoner knows his own hat color, and says
his own hat color.
The next prisoner, hearing the (correct) color of the hat of the prisoner
behind him, then has the exact same information, and can guess his own hat
correctly. Therefore, all the prisoners, with the exception of the first
guess correctly.
What about the case of hats of `n` colors? The first prisoner should say the
color
(0 * #(color 0) + 1 * #(color 1) + ... + (n - 1) * #(color (n - 1))) mod n,
where #(color i) is the number of prisoners in front of the first prisoner
wearing the ith color hat.