I struggled with this for a while and settled on using a common data structure. You might want to look into something that's FILO for this.