import java.util.Stack; /** * */ /** * @author Dinesh.Rajput * */ public class StackAsQueue { /** * @param args */ public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); for(int i = 1;i<=10;i++ ){ //stack.push(i); push(i, stack); } while(!stack.isEmpty()){ System.out.println(stack.pop()); } } private static void push(int i, Stack<Integer> stack) { Stack<Integer> temp = new Stack<Integer>(); if(stack.isEmpty()){ stack.push(i); }else{ while(!stack.isEmpty()){ int iii=stack.pop(); temp.push(iii); } stack.push(i); while(!temp.isEmpty()){ int iii=temp.pop(); stack.push(iii); } } } }Solution 2: Without Using a Temporary Stack
import java.util.Stack; public class MyQueue<Integer> { Stack<Integer> stack = new Stack<Integer>(); public boolean isEmpty(){ return stack.isEmpty(); } public void enqueue(Integer item){ stack.push(item); } public Integer dequeue(){ return pop(stack); } private Integer pop(Stack<Integer> stack){ Integer top = stack.pop(); Integer last; if(stack.isEmpty()){ return top; }else{ last = pop(stack); } stack.push(top); return last; } }
Labels: interview questions