Google Interview Question
1,223 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Google:
Items are pushed onto a stack, and therefore may be accessed in a last-in-first-out (LIFO) manner. How might you access these items in a first-in-first-out (FIFO) manner?
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (5)
1 of 1 people found this helpful
package com.google.interview2;
import java.util.Stack;
public class FifoStack{
public Stack<Object> s;
public FifoStack(Stack<Object> s){
this.s = s;
}
public void printStackInFifo(){
Stack<Object> temp = new Stack<Object>();
while (!this.s.isEmpty()){
temp.push(s.pop());
}
while (!temp.isEmpty()){
System.out.println(temp.pop());
}
}
public static void main (String[] args){
Stack<Object> s = new Stack<Object>();
s.push(5);
s.push(-9);
s.push(20);
FifoStack fs = new FifoStack(s);
fs.printStackInFifo();
}
}
Helpful Answer?
Yes |
No
Inappropriate?
http://codercareer.blogspot.com/2011/10/no-17-queue-implemented-with-two-stacks.html
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
{
Stack<T> stackA;// define two stacks, one of them will be a buffer at a time,
Stack<T> stackB;//items in stackB are in FIFO because they are always popped from stackA LIFO
public CustomQueue()
{
stackA = new Stack<T>();
stackB = new Stack<T>();
}
public void enqueue(T item)
{
stackA.push(item);//push to stackA, it keeps them in the buffer until there is a dequeue
}
public boolean empty()
{
return stackA.size()==0 && stackB.size()==0;
}
public T dequeue()
{
if( stackB.size()!=0)//if stackB is not empty, the items are in order
return stackB.pop();
else// if stackB is empty, move all items from stackA to stackB, now every item is FIFO in StackB
{
while (stackA.size()!=0)
stackB.push(stackA.pop());
return stackB.pop();
}
}
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
1 of 1 people found this helpful
by Interview Candidate: