DEV Community

özkan pakdil
özkan pakdil

Posted on

Make a Queue from using stacks in java

public class Q1 {
    private final Stack<Integer> newest =new Stack<>();
    private final Stack<Integer> oldest=new Stack<>();

    void enqueue(Integer e){
        newest.push(e);
    }

    private void shift(){
        while(!newest.empty()){
            oldest.push(newest.pop());
        }
    }

    Integer deque(){
        shift();
        return oldest.pop();
    }
}
Enter fullscreen mode Exit fullscreen mode

and below tests

class Q1Test {
    Q1 testee = new Q1();

    @Test
    void enqueue() {
        for (int i = 0; i < 10; i++) {
            testee.enqueue(i);
        }
        System.out.println(testee.deque());
        for (int i = 11; i < 22; i++) {
            testee.enqueue(i);
        }
        System.out.println(testee.deque());
    }

    @Test
    void deque() {

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!