AQueue.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. public class AQueue <T>
  2. {
  3. private T[] arr;
  4. private int front;
  5. private int end;
  6. private int count;
  7. public static class MyException extends RuntimeException
  8. {
  9. private static final long serialVersionUID = -244806549310243756L;
  10. public MyException()
  11. {
  12. super();
  13. }
  14. public MyException(String message)
  15. {
  16. super(message);
  17. }
  18. }
  19. public AQueue(int arrSize)
  20. {
  21. arr = (T[]) new Object[arrSize];
  22. front = 0;
  23. end = -1;
  24. count = 0;
  25. }
  26. public boolean isEmpty()
  27. {
  28. return (count < 1);
  29. }
  30. public void enqueue(T item)
  31. {
  32. if(count == arr.length)
  33. {
  34. T[] tmpArr = (T[]) new Object[arr.length * 2];
  35. for (int i = 0; i < count; i++)
  36. {
  37. tmpArr[i] = arr[(front + i) % arr.length];
  38. }
  39. arr = tmpArr;
  40. front = 0;
  41. end = count - 1;
  42. }
  43. end = (end + 1) % arr.length;
  44. arr[end] = item;
  45. count ++;
  46. }
  47. public T dequeue()
  48. {
  49. if (isEmpty())
  50. {
  51. throw new MyException();
  52. }
  53. T tmp = arr[front];
  54. arr[front] = null;
  55. front = (front + 1) % arr.length;
  56. count --;
  57. return tmp;
  58. }
  59. public void printArray()
  60. {
  61. for (int i = 0; i < arr.length; i++)
  62. {
  63. System.out.print(arr[i] + " ");
  64. }
  65. System.out.println();
  66. }
  67. }