Reverse method reverses elements of a queue

前端 未结 4 1049
死守一世寂寞
死守一世寂寞 2021-01-12 15:07

This is not a HW or assignment. This is something i\'m practicing myself.

Given a queue, write a Reverse method reverses elements of a queue. MyQueue remains unchan

4条回答
  •  醉梦人生
    2021-01-12 15:54

    I've used two different approaches that don't depend on your queue size. The first one uses Stack and second one - Java 8 Stream API (the fastest).

    The most effective solution for reversing queue in my tests is:

    private Queue reverse(Queue queue) {
            List collect = queue.stream()
                    .collect(Collectors.toList());
            Collections.reverse(collect);
            return new LinkedList<>(collect);
        }
    

提交回复
热议问题