队列的两种实现方式

1.数组实现队列

/**
 * @author yhd
 * @email 
 * @description 数组实现的队列  入队 出队  队列中元素个数
 * @since 2021/4/7 0:40
 * <p>
 * 分析:入队 1 2 3 4 5
 * 出队1 2 3 4 5
 */
public class Queue<T> {

    private T[] arr;

    public Queue(int size) {
        arr = (T[]) new Object[size];
    }

    private int length = 0;

    //队列中元素个数
    public int getLength() {
        return length;
    }

    //入队  入队需要修改从头到尾插入元素   并增加length
    public void push(T data) {
        if (length + 1 <= arr.length) {
            arr[length++]=data;
        } else {
            throw new RuntimeException("队列满!");
        }
    }

    //出队 需要从头到尾
    public T pop(){
        if (length==0){
            throw  new RuntimeException("队列为空,无法抛出元素!");
        }
        T data =arr[0];
        T [] temp = (T[]) new Object[arr.length];
        //5
        IntStream.rangeClosed(1, arr.length - 1).forEach(i -> temp[i - 1] = arr[i]);
        arr=temp;
        length--;
        return data;
    }
}

2.链表实现队列

/**
 * @author yhd
 * @email yinhuidong1@xiaomi.com
 * @description 使用链表实现队列
 * @since 2021/4/7 1:26
 * 1 
 * 2 1
 * 3 2 1
 * 3 2
 * 3
 * null
 */
public class Queue2 {

   LinkList linkList;

    public Queue2(){
        linkList=new LinkList();
    }

    //入栈
    public void push(int data){
        linkList.push(data);
    }

    //出栈
    public int pop(){
        return linkList.pop();
    }

    //元素个数
    public int size(){
        return linkList.getLength();
    }
    class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
        }
    }
    class LinkList {
        Node head = new Node(0);

        int length = 0;

        //入栈 头插 3 2 1
        public void push(int data) {
            if (head.next == null) {
                head.next = new Node(data);
            } else {
                Node node = new Node(data);
                node.next = head.next;
                head.next = node;
            }
            length++;
        }

        //出栈 尾删
        public int pop() {
            if (head.next == null) {
                throw new RuntimeException("栈中无元素,无法弹出!");
            }
            Node p = head.next; // 1 2 3 4 5
            Node q = head;
            while (p.next != null) {
                p = p.next;
                q = q.next;
            }
            q.next = null;
            length--;
            return p.data;
        }

        //元素个数
        public int getLength() {
            return length;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值