Advertisement
Guest User

Untitled

a guest
May 24th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. package queue;
  2.  
  3. public class ArrayQueue extends AbstractQueue {
  4. private int head = 0, tail = 0, index = 0;
  5. private Object[] elems = new Object[10];
  6.  
  7. public ArrayQueue(int s) {
  8. elems = new Object[s];
  9. }
  10.  
  11. public ArrayQueue() {
  12. elems = new Object[10];
  13. }
  14.  
  15. private int inc(int x) {
  16. return (x + 1) % elems.length;
  17. }
  18.  
  19. private int dec(int x) {
  20. return (x == 0 ? elems.length - 1 : x - 1);
  21. }
  22.  
  23. private void ensureCapacity(int capacity) {
  24. if (capacity < elems.length && elems.length <= capacity * 4) {
  25. return;
  26. }
  27.  
  28. Object[] newElems = new Object[2 * capacity];
  29. newElems = fillArray(newElems);
  30.  
  31. head = 0;
  32. tail = index;
  33. elems = newElems;
  34.  
  35. }
  36.  
  37. private Object[] fillArray(Object[] res) {
  38. assert res != null;
  39.  
  40. index = 0;
  41. for (int i = head; i != tail; i = inc(i)) {
  42. res[index++] = elems[i];
  43. }
  44. return res;
  45. }
  46.  
  47. protected void enqueueImpl(Object elem) {
  48. ensureCapacity(size + 1);
  49. elems[tail] = elem;
  50. tail = inc(tail);
  51. }
  52.  
  53. protected Object elementImpl() {
  54. return elems[head];
  55. }
  56.  
  57. protected void dequeueImpl() {
  58. //assert size > 0;
  59.  
  60. elems[head] = null;
  61. head = inc(head);
  62. ensureCapacity(size - 1);
  63. }
  64.  
  65. protected void clearImpl() {
  66. head = tail = 0;
  67. ensureCapacity(1);
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement