队列(用双向链表来实现)

一.队列的概念

队列 :只允许 在一端 进行 插入 数据操作,在 另一端 进行 删除 数据操作的特殊线性表,队列具有 先进先出 入队列 :进行插入操作的一端称为 队尾   出队列 :进行删除操作的一端称为 队头
Java 中, Queue 是个接口,底层是通过链表实现

                                                                                                                                                           

二.队列的使用

注意 Queue 是个接口,在实例化时 必须实例化LinkedList的对象 ,因为 LinkedList 实现了 Queue 接口。
例:Queue<Integer> queue= new LinkedList<>() ;
方法功能
queue.offer(val)入队列
queue.poll()(头元素)出队列
queue.peek()获取顶元素
queue.size()获取元素个数
queue.isEmpty()判断是否为空

                                                                                                                                                           

三.队列的模拟实现

public class MyQueue {
    public static void main(String[] args) {
        MyQueue q=new MyQueue();
        q.offer(1);
        q.offer(2);
        System.out.println(q.peek());
        System.out.println(q.poll());
        System.out.println(q.peek());
        System.out.println(q.size);
        System.out.println(q.isEmpty());
    }
    static class ListNode{//双链表
        public int val;
        public ListNode per;
        public ListNode next;
        public ListNode(int val){
            this.val=val;
        }
    }
    public ListNode last=null;
    public ListNode first=null;
    public int size=0;
    public void offer(int val){
        ListNode noue=new ListNode(val);
        if(size==0){
            first=last=noue;
        }else {          
  noue.per=last;
last.next=noue;
last=last.next;
        }
        size++;
    }
    public int poll(){
        if(isEmpty()){
            int sum= first.val;
            size--;
            first=first.next;
            first.per=null;
            return sum;
        }
        return -1;
    }
    public int peek(){
        if(isEmpty()){
            int sum= first.val;
            return sum;
        }
        return -1;
    }
    public boolean isEmpty(){
        if(size==0){
            return false;
        }
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值