java数据结构——链表实现队列

package Queue;



public class LinkQueue<T>{
    
    //队列,尾巴进头出
    // 链栈的节点
    private class Node<T> {
        T e;     //节点的数据域
        Node<T> next;           //后继

        public Node() {          //无参构造方法
        }

        public Node(T e, Node next) {           //有参构造方法
            this.e = e;
            this.next = next;
        }
    }

    private Node front;// 队列头,允许删除
    private Node rear;// 队列尾,允许插入
    private int size; //队列当前长度

    //初始化队列为空
    public LinkQueue() {
        front = null;
        rear = null;
    }

    //判空
    public boolean empty(){
        return size==0;
    }

    //插入
    public boolean add(T e){
        if(empty()){    //如果队列为空
            front = new Node(e,null);//只有一个节点,头尾都指向该节点,简而言之就是它既是头又是尾
            rear = front;
        }else{
            Node<T> newNode = new Node<T>(e, null);
            rear.next = newNode; //让当前尾节点的next指向新增的节点
            rear = newNode; //以新节点作为新的尾节点
        }
        size ++;
        return true;
    }

    //返回队首元素,但不删除
    public Node<T> peek(){
        if(empty()){
            throw new RuntimeException("空队列异常!");
        }else{
            return front;
        }
    }

    //出队
    public Node<T> pop(){
        if(empty()){
            throw new RuntimeException("空队列异常!");
        }else{
            Node<T> value = front; //得到队列头元素
            front = front.next;//让front引用指向原队列头元素的下一个元素
            value.next = null; //释放原队列头元素的next引用
            size --;
            return value;
        }
    }

    //队列长度
    public int length(){
        return size;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40692753/article/details/82989423