Skip to content

Latest commit

 

History

History
133 lines (100 loc) · 2.98 KB

20.Other Collections.md

File metadata and controls

133 lines (100 loc) · 2.98 KB

16.Other Collections

1. Queue

==单向==:一端操作

-队列FIFO

-优先级队列和堆栈LIFO

package com.alexanderli95.otherCollections.queue;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * 使用队列模拟银行存款业务
 */
public class Demo01 {
    public static void main(String[] args) {
        Queue<Request> queue=new ArrayDeque<Request>();
        //模拟排队情况
        for (int i=0;i<10;i++){
            final int num=i;
            queue.offer(new Request() {      //offer:如果在不违反容量限制的情况下立即执行,则将指定的元素插入到此队列中。
                @Override
                public void deposit() {
                    System.out.println("第:"+num+"个人排队办理存款业务。存款金额:"+Math.round(Math.random()*10000));
                }
            });
        }

        dealwith(queue);

    }

    //处理业务
    public static void dealwith(Queue<Request> queue){
        Request req=null;
        while(null!=(req=queue.poll())){     //poll:检索并删除此队列的头,如果此队列为空,则返回 null
            req.deposit();
        }
    }
}

interface Request{
    void deposit();
}

2. Deque

==双向==:两端操作,头或尾操作

double-ended queue,具有队列和栈性质的数据结构,双端队列中的元素可以从两端弹出,限定插入和删除操作在表的两端进行。

扩展了Queue接口,在将双端队列用作队列时,将得到FIFO行为

可用作LIFO堆栈

MyStack.java

package com.alexanderli95.otherCollections.queue;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 使用队列实现自定义堆栈
 * 1.弹栈
 * 2.压栈
 * @param <E>
 */
public class MyStack<E> {
    //容器
    private Deque<E> container=new ArrayDeque<E>();
    //容量
    private int cap;

    public MyStack(int cap) {
        this.cap = cap;
    }

    // 压栈
    public boolean push(E e){
        if(container.size()+1>cap){
            return false;
        }
        return container.offerLast(e);
    }

    //弹栈
    public E pop(){
        return container.pollLast();
    }

    //获取
    public E peek(){
        return container.peekLast();
    }

    public int size(){
        return this.container.size();
    }

}

Demo02.java

package com.alexanderli95.otherCollections.queue;

public class Demo02 {
    public static void main(String[] args) {
        MyStack<String> browserHistory=new MyStack<String>(3);
        browserHistory.push("www.google.com");
        browserHistory.push("www.bilibili.com");
        browserHistory.push("www.qq.com");
        browserHistory.push("www.csdn.com");  //容量为3,最后一条没有压入栈

        String item=null;
        while (null!=(item=browserHistory.pop())){
            System.out.println(item);
        }
    }
}