Formatted and using queue

I used a queue to speedup the implementation.