赞
踩
- 1.public class SequenceQueue<T>
- 2.{
- 3. private int DEFAULT_SIZE = 10;
- 4. //保存数组的长度。
- 5. private int capacity;
- 6. //定义一个数组用于保存顺序队列的元素
- 7. private Object[] elementData;
- 8. //保存顺序队列中元素的当前个数
- 9. private int front = 0;
- 10. private int rear = 0;
- 11. //以默认数组长度创建空顺序队列
- 12. public SequenceQueue()
- 13. {
- 14. capacity = DEFAULT_SIZE;
- 15. elementData = new Object[capacity];
- 16. }
- 17. //以一个初始化元素来创建顺序队列
- 18. public SequenceQueue(T element)
- 19. {
- 20. this();
- 21. elementData[0] = element;
- 22. rear++;
- 23. }
- 24. /**
- 25. * 以指定长度的数组来创建顺序队列
- 26. * @param element 指定顺序队列中第一个元素
- 27. * @param initSize 指定顺序队列底层数组的长度
- 28. */
- 29. public SequenceQueue(T element , int initSize)
- 30. {
- 31. this.capacity = initSize;
- 32. elementData = new Object[capacity];
- 33. elementData[0] = element;
- 34. rear++;
- 35. }
- 36. //获取顺序队列的大小
- 37. public int length()
- 38. {
- 39. return rear - front;
- 40. }
- 41. //插入队列
- 42. public void add(T element)
- 43. {
- 44. if (rear > capacity - 1)
- 45. {
- 46. throw new IndexOutOfBoundsException("队列已满的异常");
- 47. }
- 48. elementData[rear++] = element;
- 49. }
- 50. //移除队列
- 51. public T remove()
- 52. {
- 53. if (empty())
- 54. {
- 55. throw new IndexOutOfBoundsException("空队列异常");
- 56. }
- 57. //保留队列的rear端的元素的值
- 58. T oldValue = (T)elementData[front];
- 59. //释放队列的rear端的元素
- 60. elementData[front++] = null;
- 61. return oldValue;
- 62. }
- 63. //返回队列顶元素,但不删除队列顶元素
- 64. public T element()
- 65. {
- 66. if (empty())
- 67. {
- 68. throw new IndexOutOfBoundsException("空队列异常");
- 69. }
- 70. return (T)elementData[front];
- 71. }
- 72. //判断顺序队列是否为空队列
- 73. public boolean empty()
- 74. {
- 75. return rear == front;
- 76. }
- 77. //清空顺序队列
- 78. public void clear()
- 79. {
- 80. //将底层数组所有元素赋为null
- 81. Arrays.fill(elementData , null);
- 82. front = 0;
- 83. rear = 0;
- 84. }
- 85. public String toString()
- 86. {
- 87. if (empty())
- 88. {
- 89. return "[]";
- 90. }
- 91. else
- 92. {
- 93. StringBuilder sb = new StringBuilder("[");
- 94. for (int i = front ; i < rear ; i++ )
- 95. {
- 96. sb.append(elementData[i].toString() + ", ");
- 97. }
- 98. int len = sb.length();
- 99. return sb.delete(len - 2 , len).append("]").toString();
- 100. }
- 101. }
- 102.}
队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,只允许在表的后端(rear)进行插入操作。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。