Use deque as previously suggested. Cuts out the O(n^2) copying.