Created
March 10, 2013 02:22
-
-
Save spininertia/5126808 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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