Oracle Interview Question
Financial Software DevelopersCountry: India
Interview Type: In-Person
public class QueueUsingStack {
Stack<Integer> q1 = new Stack<Integer>();
Stack<Integer> q2 = new Stack<Integer>();
public void pop() {
while (q1.size() > 1)
q2.add(q1.pop());
System.out.println("POPped:" + q1.pop());
while (!q2.isEmpty())
q1.add(q2.pop());
}
public void push(int val) {
System.out.println("PUSHed:" + val);
q1.add(val);
}
/**
* @param args
*/
public static void main(String[] args) {
QueueUsingStack suq = new QueueUsingStack();
suq.push(5);
suq.push(4);
suq.push(3);
suq.push(2);
suq.push(1);
suq.pop();
suq.push(6);
suq.pop();
suq.pop();
suq.pop();
}
}
#include<iostream>
#include<stack>
using namespace std;
/* STRUCTURE OF QUEUE HAVING TWO STACKS */
struct _queue
{
stack<int> s1;
stack<int> s2;
};
/* FUNCTION TO ENQUEUE AN ITEM TO QUEUE */
void enQueue(_queue* q1, int x)
{
q1->s1.push(x);
}
/* FUNCTION TO DEQUEUE AN ITEM FROM QUEUE */
int deQueue(_queue* q1)
{
int ele=0;
if(q1->s1.empty() && q1->s2.empty())
{
printf("Error");
exit(0);
}
if(q1->s2.empty())
{
while(!q1->s1.empty())
{
int temp=q1->s1.top();
q1->s1.pop();
q1->s2.push(temp);
}
}
ele=q1->s2.top();
q1->s2.pop();
return ele;
}
/* DRIVER FUNCTION TO TEST ANOVE FUNCTIONS */
int main()
{
/* CREATE A QUEUE WITH ITEMS 1 2 3*/
_queue *q = new _queue;
enQueue(q, 1);
enQueue(q, 2);
enQueue(q, 3);
/* DEQUEUE ITEMS */
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
return 0;
}
we can implement the queue using two stacks..for adding we can pop the stack and put it in another stack...that will reverse the stack...now we can push the new element on the second stack and then we can pop the entire stack back into the first stack....for deleting from front we can simply....push in the stack.
- Anonymous February 09, 2014