Java 实现队列

链式存储结构实现

public class LinkQueue<E> {
    //链栈的节点
    private class Node<E>{
        E e;
        Node<E> next;
        public Node(){
        }

        public Node(E e,Node<E> next){
            this.e = e;
            this.next = next;
        }
    }
    private Node<E> head; //队列头
    private Node<E> tail; //队列尾
    private int size; //队列当前长度

    public LinkQueue(){
        this.head = null;
        this.tail = null;
    }

    //判空
    public boolean isEmpty(){
        return head == null;
    }

    //入队
    public boolean add(E e){
        if(isEmpty()){ //如果队列为空
            head = new Node<E>(e,null);
            tail = head; //只有一个节点,队列头,队列尾都指向该节点
        }else{
            Node<E> newNode=  new Node<E>(e,null); //新节点元素
            tail.next = newNode; //队列尾的next指向新节点
            tail = newNode;
        }
        size++;
        return true;
    }

    //出队
    public E poll() {
        if (isEmpty())
            throw new NullPointerException("元素为空!");
        Node<E> node = head; //队列头元素
        head  = head.next;  //让head引用指向下一个元素
        node.next = null; //释放原队列头元素的next引用
        size--;
        return node.e; //返回队列头
    }

    //查看队列头元素
    public E peek(){
        if(isEmpty()){
            throw new RuntimeException("空队列异常!");
        }else{
            return head.e;
        }
    }
    
    //长度
    public int length(){
       return size;
    }
    

顺序存储结构实现

import java.util.Arrays

public class ListQueue<E> {
    Object[] queue;
    int size;

    public ListQueue(){
        queue = new Object[10];
    }
    public ListQueue(int size){
        queue = new Object[size];
    }

    public boolean isEmpty(){
        return size==0;
    }
    //入队
    public void add(E e){
        //判断长度 是否要扩容
        if(size >= queue.length){
            int len = queue.length+10;
            queue = Arrays.copyOf(queue,len);
        }
        queue[size++] = e;
    }
    
    //出队
    public E poll(){
        if(isEmpty())
            throw new NullPointerException("元素为空!");
        E data = (E)queue[0];
        System.arraycopy(queue,1,queue,0,size-1);
        size--;
        return data;
    }
    
    //查看队列头元素
    public E peek(){
        return (E)queue[0];
    }

    //长度
    public int length(){
        return size;
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值