Ring transformations in reactions of heterocyclic compounds with nucleophiles