How does evolution explain the similar legs in mammals and explain why the function differently?

Answer/Explanation:
These are examples of homologous structures. These are derived from common ancestors , however, they do not necessarily perform the same function. A good example is the vertebrate forelimbs like the ones shown here.
These limbs all have the same basic pattern of bones. They inherited this pattern from a common ancestor, but they now have different functions. This is an example of divergent evolution