java代码简单实现队列

1. 基于链表简单实现

 1 import lombok.AllArgsConstructor;
 2 import lombok.Data;
 3 import lombok.NoArgsConstructor;
 4 
 5 /**
 6  * @author <a href="mailto:yanwu0527@163.com">baofeng Xu</a>
 7  * @date 2019/12/10
 8  * <p>
 9  * describe:
10  */
11 public class LinkedQueue<T> {
12     private static final Integer DEFAULT_SIZE = 10;
13     /*** 队头 */
14     private Node front;
15     /*** 队尾 */
16     private Node rear;
17     /*** 长度 */
18     private Integer size;
19     /*** 当前所在位置 */
20     private Integer index;
21 
22     public LinkedQueue() {
23         this(DEFAULT_SIZE);
24     }
25 
26     /**
27      * 初始化队列
28      *
29      * @param len
30      */
31     public LinkedQueue(Integer len) {
32         if (len <= 0) {
33             throw new IndexOutOfBoundsException();
34         }
35         size = len;
36         index = -1;
37     }
38 
39     /**
40      * 入队
41      *
42      * @param t
43      * @return
44      */
45     public boolean enqueue(T t) {
46         if (index >= size - 1) {
47             // ----- 超出队列容量
48             return false;
49         }
50         Node newNode = new Node(t, null);
51         if (index == -1) {
52             // ----- 当队列中只有一个元素时,队头和队尾为同一个元素
53             front = rear = newNode;
54         } else {
55             // ----- 将新元素置为原有队尾的next,并将新元素置为新的队尾
56             rear.next = newNode;
57             rear = newNode;
58         }
59         index++;
60         return true;
61     }
62 
63     /**
64      * 出队
65      *
66      * @return
67      */
68     public Node dequeue() {
69         if (front == null) {
70             return null;
71         }
72         // ----- 将队头返回,并将队头的next置为新的队头
73         Node result = front;
74         front = front.next;
75         index--;
76         return result;
77     }
78 
79     @Data
80     @NoArgsConstructor
81     @AllArgsConstructor
82     private class Node {
83         private T data;
84         private Node next;
85     }
86 
87     public static void main(String[] args) {
88         LinkedQueue<Integer> queue = new LinkedQueue<>();
89         for (int i = 0; i < DEFAULT_SIZE + 1; i++) {
90             System.out.println("enqueue: " + queue.enqueue(i) + ", item: " + i);
91         }
92         for (int i = 0; i < DEFAULT_SIZE + 1; i++) {
93             System.out.println("dequeue: " + queue.dequeue());
94         }
95     }
96 }

2. 基于数组实现队列

原文地址:https://www.cnblogs.com/yanwu0527/p/12019547.html