基础数据结构 Java 实现队列 链表实现 迭代器

jdk1.8

**

基础数据结构——先进先出队列

**

FIFO,先进先出策略集合模型

队列的使用及实现

  • 先进先出队列(或简称队列): 是一种基于先进先出策略的集合类型。

  • 场景:

    1. 按照任务的产生顺序完成它们的策略。剧院门前排队的人,收费站前排队的汽车或计算机上某软件中等待处理的任务。
    2. 服务型策略的基本原则都是公平。优先服务等待最久的人,正是先进先出策略。

Java集合库提供的栈使用

public static void main(String[] args) {
    Deque<Integer> q;
    q = new LinkedList<>();
    int [] arr = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };
    for (int x : arr){
        q.offer(x);
        //push方法是头填,因此和pop连用可实现栈
        //offer方法是尾填,因此队列使用这个
    }
    while ( !q.isEmpty() )
    {
        //pop方法头出
        System.out.print(q.pop()+"\t");
    }
}

链表实现队列

import java.util.Iterator;

/**
     * @Auther: Charherogit
     * @Package: DataStructure.basic
     */
public class ListQueue<Item> implements Iterable {

    private Node first;
    private Node last;
    private  int N;

    private class Node{
        Item item;
        Node next;
    }

    public boolean isEmpty(){ return first == null; }
    public int size(){ return N; }

    //表尾添加元素
    public void offer(Item item){
        Node oldlast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else oldlast.next = last;
        N++;
    }

    //表头删除元素
    public Item pop(){
        Item item = first.item;
        first = first.next;
        if (isEmpty()) last = null;
        N--;
        return item;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item>{

        private Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        public void remove(){}

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
}

队列的算法应用

  • BFS广度优先遍历

    栈在算法中一个应用则是广度优先遍历的应用。在各种树的模型中,进行树的层次遍历,使用队列是最好的选择。

    从层次遍历的特点可以基本推出,队列适合做树的层数、树的左右视图、锯齿遍历以及对称树相关的题。

    除了树的各种问题以外,BFS令一个较为常用的是结合Set、Map等来寻找最短路径问题。一般使用广度优先遍历寻找,然后使用Set去重,即是这类问题的题解思路。


有兴趣的关注我的公众号,一起学习交流啊
在这里插入图片描述

转到 》广度优先遍历


上一篇 》


下一篇 》背包


返回 》数据结构

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值