1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
package com.example.datastructure; /** * 使用顺序表(数组)实现循环队列 * 初始化:head = tail = 0; * 入队: tail = (tail+1)%N * 出队: head = (head+1)%N * 判断队列空: head== tail * 判断队列满: (tail+1)%N == head * 队列长度: (N+tail-head)%N * */ public class LoopQueue {
Object[] queue; int len; int head = 0 , tail = 0;
public LoopQueue(int len) { this.queue = new Object[len]; this.len = len; }
/** * 入队 * 队列满的条件:(tail+1)%len == head * */ public Object enQueue(Object o){ if ((tail+1)%len == head){ System.out.println("queue is full"); return null; } queue[tail] = o; tail = (tail+1)%len; // tail 回卷++, return o; }
/** * 出队 * 队列空的条件: head == tail * */ public Object deQueue(){ if (head == tail){ System.out.println("Queue is empty"); return null; } Object o = queue[head]; head = (head+1) % len; return o; }
public int size(){ return (this.len+tail-head)%this.len; }
public static void main(String[] args) { LoopQueue queue = new LoopQueue(100); for (int i = 0; i < 7; i++) { queue.enQueue(i); } System.out.println(queue.size()); for (int i = 0; i < 7; i++) { System.out.println(queue.deQueue()); } System.out.println(queue.size()); } }
|
近期评论