Salesforce Interview Question

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

Interview Answers

Anonymous

Jan 29, 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

Mar 14, 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(); } }