Skip to content

Instantly share code, notes, and snippets.

@spininertia
Created March 10, 2013 02:22
Show Gist options
  • Save spininertia/5126808 to your computer and use it in GitHub Desktop.
Save spininertia/5126808 to your computer and use it in GitHub Desktop.
package chapter3;
import java.util.Stack;
/*
* Career Cup 3.5
* Implement a MyQueue class which implements a queue using two stacks.
*/
public class C3P5 {
static class MyQueue {
Stack<Integer> enqueueStack = new Stack<Integer>();
Stack<Integer> dequeueStack = new Stack<Integer>();
public void enqueue(int data) {
enqueueStack.push(data);
}
public int pop() {
if (dequeueStack.isEmpty())
while (!enqueueStack.isEmpty())
dequeueStack.push(enqueueStack.pop());
return dequeueStack.pop();
}
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment