Unification Functions
Rather than thinking about this in terms of substitutions, you might find it useful to think about this in terms of equalities that you can infer.

In the first step, you inferred that $w=Y$.

In the second step, you inferred that $X=p(Z)$.

In the third step, you inferred that $X=Z$.

It follows that you can infer $Z=p(Z)$.  So we know $X=Z=p(Z)$ and $w=Y$.

Of course, if you can infer that two things are equal, you can substitute one for the other.  But maybe it's easier to think about unification as being a way to keep track of which things are equal (which in turn helps you know which substitutions you can make).  Hope this helps make this kind of situation feel more intuitive.