Why don't you use a Stack or queue?