There are a number of possible reasons for this. Firstly, it is important to see this story as the development of Bilbo Baggins as a hero. Initially, at the beginning of the story, he does not have much that is heroic about him. It is interesting that he is shown to meet the trolls but feels he couldn't return to his friends, the dwarves, to warn them, without proving himself to them as a thief:
...somehow he could not go straight back to Thorin and Company empty-handed. So he stood and hesitated in the shadows. Of the various burglarious proceedings he had heard of, picking the trolls' pockets seemed the least difficult, so he crept behind a tree just behind William.
Of course, the most sensible thing for Bilbo to have done would have been to have warned his friends, but the way that he gives in to pride and then also gets the whole company in trouble shows how inexperienced he is at this stage of the journey. This of course sets Bilbo up for his moment of heroism when he saves the dwarves from both the spiders and the elves later on in the novel.
A second reason for the troll episode occurring without Gandalf is to indicate the way that the company is going to encounter difficulties that will be more challenging than trolls, and this increases suspense. If the first real difficulty that they encounter is only solved through the serendipitous arrival of Gandalf, what will happen later on when they encounter more challenging difficulties and do not have his aid?