It's not a trick, its a skill. You need to first learn how to identify a melodic idea and remember it. Then you learn to recognize the recurrence of that idea or a variation on it. As you hear different ideas in the melody you assign a letter to each one. Writing these letters down as you hear the ideas will produce a map of the structure of the song, known to musicians as the "song form" or the "form" of the song.
for example you would assign the letter a to the first melodic idea. often that melodic idea repeats itself and then gets followed by a contrasting idea. So you would map that as aab. Then the first melodic idea (a) might appear again to complete the section. So now you have a section that you have mapped as aaba. Suppose that's the verse of the song and a second verse follows immediately. Now we have mapped out aaba aaba.
Lets say that a chorus occurs next. the ideas in the chorus could be anything for the purposes of this discussion, so lets say they map out as (for example) c c d
Lets also say that we hear another verse that maps as aaba.
Our entire song form might look like this now
Verse 1 aaba
Verse 2 aaba
Verse 3 aaba
Notice that you could look at form of the song as verse, verse, chorus, verse. If we think of the verse as one idea (A) and the chorus as another idea (B) the entire song form is now AABA. Each A in the AABA song form is itself an aaba. Nice!
You can use this technique to describe the structure of any musical piece, and it is a huge part of orchestral composition. Its also the difference between random noodling and jazz improvisation that makes sense. If you listen to any professional jazz musician, they aren't just blasting out notes. They are playing song form and using the technique of theme and variations to impose structure and meaning on their improvisations.