Generally speaking, if someone can determine where your song came from and/or overlay a song over yours and it sounds remarkably similar, they can make a case that you have stolen the idea, or committed plagiarism. That doesn’t mean that a lot of songs that are similar in structure aren’t written all of the time without necessarily prior knowledge of other songs like them.
If you would like to try an approach just to see how it works and to experiment with the craft of songwriting, there is something that I have done just to mess around and sometimes it yields interesting results. I take an interesting riff or chord progression, and I reverse it. Of course, by reversing a melody or riff, there can be unusual melodic or harmonic resolutions that don’t quite work, so I’ll adjust them so that it does. In essence, I’ve made a whole new melody or progression but it got its start by reversing another melody I had heard.
Again, I am not suggesting this as a literal method to writing songs but as an exercise to listen to melodies in a different way, perhaps to come up with your own variations. To borrow from classical music, Rachmaninoff is famous for his variations on a theme composed by Paganini. He’s famous for a lot of other music too, of course, but as a kid growing up, I really enjoyed hearing these multiple variations, and how he was able to make so many different melodies, harmonies, and musical pieces from another piece of music. The key to Rachmaninov’s example here, though, is he gave complete credit to the original source material.
I have borrowed chord progressions from other songs as have many songwriters but I don’t out and out steal the song. I may use the general chord progression but I change it and add additional chords and the melody to make it a completely different song. While you can still hear the influence on certain parts of my song it doesn’t sound exactly like the song that influenced it. I love the chord progression in the song Little Red Corvette and used the intro chord profession but my song definitely will never be mistaken for LRC.
To answer your question I would say it depends on how you do it. If it sounds too much like the song you are borrowing from you could be open to copyright infringement.