Amateurs think comedians walk on stage and just riff about whatever is in their head at the moment - or comics riff off topics that come up in bantering with the audience. And they also think great comedians have a special skill to create funny material "spontaneously."
This is a misperception of reality. Comedians do not create their act 100% as they go along. The art is not to make it up on the spot, but rather to make it appear as if everything is made up on the spot. Here's one way to do that.
Sometimes an audience member will ask a question or yell out something and you just happen have a bit in your act scheduled for later that fits in with their comment. Jump immediately to it and do that part of your prepared act. If you have another chunk of material that fits in, do it as well to boost laughs even if you hadn't planned on using it.
Keep in mind in that case, you may have to drop something from your planned set so as not to go over time. When done with the "Ad-libbed" material, loop back into your act where you left off.
This is what sets the pros off from the hacks. Not necessarily the ability to make it up 100%. But rather the ability to bring the material out in such a way as to look spontaneous. Lenny Bruce, who was responsible to a great degree for creating this "in the moment" style, writes in his biography, "People seem to think I make my act up as I go along. I don't. I know everything I'm going to say. I just don't know what order I'm going to say it in."
That is the FIRST sentence of his autobiography.
What about public speaking? Whenever possible, answer the audience member's question, query, or offhand comment with a prepared chunk that closely matches it and then loop back into your prepared speech where you got interrupted.
Where do you get these chunks? Anticipate all possible types of interruptions your particular speech might generate and prepare for it. Or you could simply say, "yes" - repeat what they said then a "but/and/or..." and continue with what you were just getting ready to say next.
When you get an unplanned comment from a listener and you can respond with a memorized, but appropriate chunk, audience members will leave the venue thinking you are a comedy genius. Because they saw you "improvise" a one, three, six, whatever minute bit in response to an on-the-spot-comment. You had to be "making it up" because how could you "know" that audience member was gonna say that?
Believe me - twenty-five years in comedy clubs producing shows with Robin Williams, Paula Poundstone, Jerry Seinfeld, Dana Carvey, Margaret Cho, and dozens more . . . they DON'T MAKE EVERYTHING UP ON THE SPOT.