Advertisement
RaquelAmbrozio

FIFO

Sep 30th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. package adt.queue;
  2.  
  3. public class CircularQueue<T> implements Queue<T> {
  4.  
  5. private T[] array;
  6. private int tail;
  7. private int head;
  8. private int elements;
  9.  
  10. public CircularQueue(int size){
  11. array = (T[])new Object[size];
  12. head = -1;
  13. tail = -1;
  14. elements = 0;
  15. }
  16.  
  17. @Override
  18. public void enqueue(T element) throws QueueOverflowException {
  19. if(element == null)
  20. return;
  21. if(this.isFull())
  22. throw new QueueOverflowException();
  23. if(this.isEmpty()){
  24. this.tail++;
  25. this.head++;
  26. this.elements++;
  27. this.array[head] = element;
  28. }else {
  29. this.tail = (tail+1) % this.array.length;
  30. this.elements++;
  31. this.array[tail] = element;
  32. }
  33. }
  34.  
  35. @Override
  36. public T dequeue() throws QueueUnderflowException {
  37. Object out;
  38.  
  39. if(this.isEmpty())
  40. throw new QueueUnderflowException();
  41. if(this.head == this.tail){
  42. out = this.array[head];
  43. this.head--;
  44. this.tail--;
  45. this.elements--;
  46. return (T) out;
  47. }else{
  48. out = this.array[head];
  49. this.head = (head+1) % array.length;
  50. this.elements--;
  51. return (T) out;
  52. }
  53. }
  54.  
  55. @Override
  56. public T head() {
  57. return this.isEmpty() ? null : this.array[head];
  58. }
  59.  
  60. @Override
  61. public boolean isEmpty() {
  62. return this.tail == -1;
  63. }
  64.  
  65. @Override
  66. public boolean isFull() {
  67. return ((this.tail+1) % array.length) == this.head;
  68. }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement