Reverse method reverses elements of a queue

前端 未结 4 1097
死守一世寂寞
死守一世寂寞 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:39

    You can do this without any other arrays or lists, just by recursion:

    public static  Queue flip(Queue q) {
        Queue ret = new Queue<>();
        recursiveFlip(q, ret);
        return ret;
    }
    
    private static  void recursiveFlip(Queue src, Queue dest) {
        T buffer = src.dequeue();
        if(!src.isEmpty()) {
            recursiveFlip(src, dest);
        }
        dest.enqueue(buffer);
    }
    

    First elements will be stacked in "shallow" part of the stack, while last elements in "deeper" part, and when recursion reaches the end, the "deeper" values will be added first and "shallow" last.

    But note that each one element means one step deeper into recursion, so stack overflow error will occur if the queue is too big.

    Also, the original queue will not "survive" the flip.

提交回复
热议问题