队列

队列

      队列是一种先进先出的数据结构,是一种只能在一段插入,在另一端删除的线性表,按照先进先出的原则存储数据。

1. 队列的API设计

2. 队列的代码实现

public class Queue<T>{
    private Node head;
    private int N;
    private Node last;

    private class Node{
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    public Queue() {
        this.head = new Node(null,null);
        this.last = null;
        this.N = 0;
    }
    //判断队列是否为空
    public boolean isEmpty(){
        return N==0;
    }
    //队列中元素的个数
    public int size(){
        return N;
    }
    //向队列中插入元素
    public void enqueue(T t){
            //当前尾结点为空
        if (last == null){
            last = new Node(t,null);
            head.next = last;
        }else {
            //当前尾结点不为空
            Node oldLast = last;
            last = new Node(t,null);
            oldLast.next = last;
        }
        N++;
    }
    //从队列中拿出元素
    public T dequeue(){
        if (isEmpty()){
            return null;
        }
        Node oldFirst = head.next;
        head.next = oldFirst.next;
        N--;
        if (isEmpty()){
            last = null;
        }
        return oldFirst.item;
    }
}
posted @ 2020-07-22 23:30  zuzuzu_code  阅读(103)  评论(0)    收藏  举报