当前位置:   article > 正文

数据结构之队列(java)_取一个队列中固定位置的元素java

取一个队列中固定位置的元素java

队列

先进先出 FIFO,在非空队列中,队首指针指向队头元素,队尾指针指向队尾元素的下一个位置。

顺序队列中的假溢出现象:(front:头指针,rear:尾指针)

循环队列

循环队列充分利用了系统分配的空间,克服了“假溢出”现象。方法:将队列看成是一个首尾相接的圆环。

约定:rear所指的位置始终为空

队列为空时:front == rear;

队列满时:(rear+1) % size == front;(size:队列的空间大小)

  1. class CQue{
  2. //循环队列
  3. private int size = 5;
  4. private int[] array;
  5. int front,rear;
  6. public CQue() {
  7. array = new int[this.size];
  8. front = rear =0;
  9. }
  10. /**
  11. * 入队
  12. * @param data
  13. * @throws Exception
  14. */
  15. public int insert(int data) throws Exception {
  16. if (isFull()) {
  17. throw new Exception("queue is full !");
  18. }
  19. this.array[rear] = data;
  20. this.rear = (this.rear+1)%this.size;//移动队尾指针
  21. return this.rear;//返回队尾指针的位置
  22. }
  23. /**
  24. * 出队
  25. * @return
  26. * @throws Exception
  27. */
  28. public int remove() throws Exception {
  29. if (isEmpty()) {
  30. throw new Exception("queue is empty !");
  31. }
  32. int data =array[front]; //获取队首元素
  33. this.front = (this.front+1)%this.size;//移动队首指针
  34. return data;
  35. }
  36. /**
  37. * 判断是否为空
  38. * @return
  39. */
  40. public boolean isEmpty() {
  41. return this.front == this.rear;
  42. }
  43. /**
  44. * 判断队列是否满了
  45. * @return
  46. */
  47. public boolean isFull() {
  48. return ((this.rear + 1) % this.size) == this.front;
  49. }
  50. public int getSize() {
  51. return size;
  52. }
  53. public void setSize(int size) {
  54. this.size = size;
  55. }
  56. }
  57. public class MyQueue {
  58. public static void main(String[] args) throws Exception {
  59. CQue queue = new CQue();
  60. System.out.println(queue.getSize() + "--"+queue.isEmpty() +"--"+queue.isFull());
  61. System.out.println(queue.insert(0));
  62. System.out.println(queue.insert(1));
  63. System.out.println(queue.insert(2));
  64. System.out.println(queue.insert(3));
  65. System.out.println(queue.isFull());
  66. //queue.insert(4);
  67. //System.out.println(queue.isFull());
  68. System.out.println(queue.remove());
  69. System.out.println(queue.remove());
  70. System.out.println(queue.remove());
  71. System.out.println(queue.remove());
  72. System.out.println(queue.remove());
  73. }
  74. }

 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号