- 1 public class LinkQueue {
- 2 3 //链的数据结构
- 4 private class Node {
- 5 public T data;
- 6 public Node next;
- 7 //无参构造函数
- 8 public Node() {}
- 9 10 public Node(T data, Node next) {
- 11 this.data = data;
- 12 this.next = next;
- 13
- }
- 14
- }
- 15 //队列头指针
- 16 private Node front;
- 17 //队列尾指针
- 18 private Node rear;
- 19 //队列长度
- 20 private int size = 0;
- 21 22 public LinkQueue() {
- 23 Node n = new Node(null, null);
- 24 n.next = null;
- 25 front = rear = n;
- 26
- }
- 27 28
- /**
- 29 * 队列入队算法
- 30 * @param data
- 31 * @author WWX
- 32 */
- 33 public void enqueue(T data) {
- 34 //创建一个节点
- 35 Node s = new Node(data, null);
- 36 //将队尾指针指向新加入的节点,将s节点插入队尾
- 37 rear.next = s;
- 38 rear = s;
- 39 size++;
- 40
- }
- 41 42
- /**
- 43 * 队列出队算法
- 44 * @return
- 45 * @author WWX
- 46 */
- 47 public T dequeue() {
- 48
- if (rear == front) {
- 49
- try {
- 50
- throw new Exception("堆栈为空");
- 51
- } catch(Exception e) {
- 52 e.printStackTrace();
- 53
- }
- 54
- return null;
- 55
- } else {
- 56 //暂存队头元素
- 57 Node p = front.next;
- 58 T x = p.data;
- 59 //将队头元素所在节点摘链
- 60 front.next = p.next;
- 61 //判断出队列长度是否为1
- 62
- if (p.next == null) 63 rear = front;
- 64 //删除节点
- 65 p = null;
- 66 size--;
- 67
- return x;
- 68
- }
- 69
- }
- 70 71
- /**
- 72 * 队列长队
- 73 * @return
- 74 * @author WWX
- 75 */
- 76 public int size() {
- 77
- return size;
- 78
- }
- 79 80
- /**
- 81 * 判断队列是否为空
- 82 * @return
- 83 * @author WWX
- 84 */
- 85 public boolean isEmpty() {
- 86
- return size == 0;
- 87 88
- }
- 89 90
- }
来源: