Microsoft Interview Question
SDE-2sCountry: United States
Interview Type: In-Person
// the idea is to add the push-ed item to the queue and then rotate the queue
package com.home.careercup;
import java.util.LinkedList;
import java.util.Queue;
public class StackWithQueue <T>{
private Queue <T> q = new LinkedList<>();
void push (T e) {
q.offer(e);
if (q.size() > 1){
for (int i = 0; i <q.size() -1 ; i++) {
q.offer(q.remove());
}
}
}
T pop (){
return q.isEmpty() ? null : q.remove();
}
public static void main(String[] args) {
StackWithQueue <String> stack = new StackWithQueue<>();
for (String s: new String [] {"a", "b", "c", "d"}){
stack.push(s);
}
String pop =null;
while ( null !=(pop = stack.pop())){
System.out.println(pop);
}
}
}
Object remove(Stack<Object> s){
- Mani K December 04, 2017if(s.size()==1){
return s.pop();
}
Object ele=s.pop();
Object res=remove(s);
s.push(ele)
return res;
}