【code基础】队列

队列的定义

Queue的实现类有LinkedList和PriorityQueue 最常用的实现类是LinkedList

  • 队列通常(先进先出)的方式排序各个元素,在 FIFO 队列中,所有的新元素都插入队列的末尾。
  • 其他种类的队列可能使用不同的元素放置规则。每个 Queue 实现必须指定其顺序属性。如优先级队列和 LIFO 队列(或堆栈):
    • 优先级队列根据提供的比较器或元素的自然顺序对元素进行排序,
    • LIFO 队列(或堆栈)按 LIFO(后进先出)的方式对元素进行排序
public class QueueMain {
    public static void main(String[] args) {
        MyQueue1 q = new MyQueue1();
        q.enQueue(5);
        q.enQueue(3);
        if (!q.isEmpty()) System.out.println(q.Front()); //5
        q.deQueue();
        if (!q.isEmpty()) System.out.println(q.Front()); //3
        q.deQueue();
        q.enQueue(4);
        if (!q.isEmpty()) System.out.println(q.Front()); //4

    }
}

队列的操作

  • 队列的数据结构为Queue,内置实现是LinkList
  • 队列的获取队首元素为q.peek()
  • 队列入队操作位q.offer(x)
  • 队列的出队为q.poll()
  • 队列的长度为q.size()
public class InnerQueueMain {
    public static void main(String[] args) {
        // 1. Initialize a queue.
        Queue<Integer> q = new LinkedList<>();
        Queue<Integer> q2 = new ArrayDeque<>();

        // 2. Get the first element - return null if queue is empty.
        System.out.println("The first element is: " + q.peek()); //null

        // 3. Push new element.
        q.offer(5);
        q.offer(13);
        q.offer(8);
        q.offer(6);

        // 4. Pop an element.
        q.poll(); //5

        // 5. Get the first element.
        System.out.println("The first element is: " + q.peek()); //13
        // 7. Get the size of the queue.
        System.out.println("The size is: " + q.size());  //3
    }
}
posted @   xiaoyu_jane  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示