Salesforce interview question

Implement Que using 2 stacks. write test cases for it.

Interview Answers

Anonymous

29 Jan 2016

When queuing push the elements in the first stack, and when dequeuing pop from the first stack and push into the second stack until the first stack is empty. At that point, pop the second stack and that is your dequeued element.

1

Anonymous

14 Mar 2016

class Queue { Stack queueStack; Queue() { queue = new Stack(); } void add(int x) { Stack tempStack = new Stack(); if(!queueStack.isEmpty()) { tempStack.push(queueStack.pop()); } tempStack.push(x) while(!tempStack.isEmpty()) { queueStack.push(tempStack.pop()); } } int poll() { if(!queueStack.isEmpty()) queueStack.pop(); } int peek() { if(!queueStack.isEmpty()) queueStack.top(); } }