본문 바로가기

Algorithm

Reverse Queue with Java

반응형
import java.util.Queue;
import java.util.Stack;

public class ReverseQueue {
    public static void main(String[] args) {
        Queue<Integer> q = new java.util.LinkedList<>();
        q.offer(1);
        q.offer(2);
        q.offer(3);
        q.offer(4);
        q.offer(5);
        System.out.println(q);
        q = reverse(q);
        System.out.println(q);
    }

    public static Queue<Integer> reverse(Queue<Integer> q) {
        Stack<Integer> stack = new Stack<>();
        while(!q.isEmpty()) {
            stack.push(q.poll());
        }
        while(!stack.isEmpty()) {
            q.offer(stack.pop());
        }
        return q;
    }
}

//output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
반응형

'Algorithm' 카테고리의 다른 글

Make Queue with 2 stack in Java  (0) 2024.04.06
Reverse Queue with Stack in Java  (0) 2024.04.06
BFS and DFS with Java  (1) 2024.04.06
BFS and DFS with Java  (0) 2024.03.24
DFS and BFS  (0) 2024.03.24