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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay