Well, they have to co-opt or adapt structures that they already have. Dolphins and whales evolved from mammals, which means they already had a very complicated and sophisticated way of obtaining oxygen from the environment. The niche that was filled, however, was one that involved spending more time in the water, so over many generations the populations of mammals that eventually gave rise to these mammals adapted to a life of water-dwelling. The path of least resistance for entering the water niche was modifying existing traits at the expense of having to come up and breathe air every once in a while, instead of re-inventing the wheel when it comes to oxygen utilization.
When land creatures evolved, embryologically they co-opted the gill structure to give rise to other structures. In my embryology coursework, we learned how the pharyngeal arches are analogous to gills. In humans, the pharyngeal arches give rise to skull bones, connective tissue of the head, cranial blood vessels, and some endocrine organs, among other things. Point being - you really can't go back once you've made that drastic a change to the body plan. Thus, dolphins and whales don't have gills.