Three captives

Cannibals ambush a safari in the jungle and capture three men. The cannibals give the men a single chance to escape uneaten.

The captives are lined up in order of height, and are tied to stakes. The man in the rear can see the backs of his two friends, the man in the middle can see the back of the man in front, and the man in front cannot see anyone. The cannibals show the men five hats. Three of the hats are black and two of the hats are white.

Blindfolds are then placed over each man's eyes and a hat is placed on each man's head. The two hats left over are hidden. The blindfolds are then removed and it is said to the men that if one of them can guess what color hat he is wearing they can all leave unharmed.

The man in the rear who can see both of his friends' hats but not his own says, "I don't know". The middle man who can see the hat of the man in front, but not his own says, "I don't know". The front man who cannot see ANYBODY'S hat says "I know!"

How did he know the color of his hat and what color was it?

(1) The only way the man in the rear can know the color of his hat is if both men in front wore white hats, and then the man in the rear would know that he is wearing a black hat.
Since he cannot tell the color of his hat, the two men in front know that they can not both be wearing white hats.

(2) If the middle man saw that the man in front had a white hat, he (the middle man) would know that he is wearing a black hat (or else the rear man would know that he was wearing a black hat).

(3) Because neither the rear man nor the middle man knows for certain what color hat they are wearing, the man in front can be positive that he is wearing a black hat.