Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import java.util.NoSuchElementException;
  2. import java.util.Queue;
  3.  
  4. /**
  5. * Simple implementation of Stack using two Queues
  6. *
  7. * @author CIS-121 Staff
  8. * @version 1.0 10/11/2011
  9. * @param <K>
  10. */
  11.  
  12. public class MyStack<K> {
  13. private Queue<K> q1, q2;
  14.  
  15. /**
  16. * Create a new stack with given queues.
  17. */
  18. public MyStack(Queue<K> q1, Queue<K> q2) {
  19. this.q1 = q1;
  20. this.q2 = q2;
  21. }
  22.  
  23. /**
  24. * Push an element onto the top of the stack.
  25. * @param k The element to push.
  26. */
  27. public void push(K k) {
  28. // add "k" to empty queue
  29. if (q1.isEmpty()) {
  30. q1.add(k);
  31.  
  32. //append all elements of nonempty queue to empty queue
  33. while(!q2.isEmpty()) {
  34. q1.offer(q2.remove());
  35. }
  36.  
  37. } else {
  38. q2.add(k);
  39.  
  40. //append all elements of nonempty queue to empty queue
  41. while(!q1.isEmpty()) {
  42. q2.offer(q1.remove());
  43. }
  44. }
  45. }
  46.  
  47. /**
  48. * Pops the top element off the stack.
  49. * @return The top element on the stack.
  50. * @throws NoSuchElementException when popping an empty stack.
  51. */
  52. public K pop() throws NoSuchElementException {
  53. if (this.isEmpty()) {
  54. throw new NoSuchElementException();
  55. } else if (q1.isEmpty()) {
  56. return q2.remove();
  57. } else if (q2.isEmpty()) {
  58. return q1.remove();
  59. }
  60. return null; //should never happen, put it in for eclipse to compile.
  61.  
  62. }
  63.  
  64. public boolean isEmpty() {
  65. return (q1.isEmpty() && q2.isEmpty());
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement