第五关|队列和Hash的特征

1、Hash基础

 Hash在工程中大量使用,在算法中较少使用。

哈希(Hash)也称为散列,就是把任意长度的输入,通过散列算法,变换成固定长度的输出,这个输出值就是散列值。

取模后是几就存到下标是几,但会引起碰撞。(不同输入取模后hash值相同)

解决冲突:

  1. 开放定址法:                                                                                                                             假定2%7,在索引为2的地方存了2。之后16%7,本应也在索引为2的地方存,但已经存2,于是以顺序的方式(3、4、5、...)找为空的位置去存,若3有值,4为空,则16最终存入索引为4的位置。
  2. 链地址法:                                                                                                                                 将哈希表的每个单元作为链表的头结点,所有哈希地址为i的元素构成一个同义词链表。即发生冲突时就把该关键字链在以该单元为头结点的链表的尾部。这种处理方式代价高,需要优化很多问题。

2、队列基础

  • 像排队一样,刚来的人在最后,队头的人办完事情最先离开
  • FIFO先进先出

基于链表实现队列:

public class LinkQueue {

    private Node front;//队头
    private Node rear;//队尾
    private int size;

    public LinkQueue(){
        front = new Node(0);
        rear = new Node(0);
    }

    //入队
    public void push(int value){
        Node newNode = new Node(value);
        Node temp = front;
        while(temp.next != null){
            temp = temp.next;
        }

        temp.next = newNode;
        rear = newNode;
        size++;
    }

    //出队
    public int pull(){

        if(front.next == null){
            throw new NullPointerException("空队列,无法出队");
        }

        Node firstNode = front.next;
        front.next = firstNode.next;
        size--;

        return firstNode.data;
    }

    //遍历队列
    public void traverse(){
        Node temp = front.next;
        while(temp != null){
            System.out.print(temp.data + "\t");
            temp = temp.next;
        }

    }

    static class Node{
        public int data;
        public Node next;

        public Node(int data){
            this.data = data;
            next = null;
        }
    }

    public static void main(String[] args){

        LinkQueue LinkQueue = new LinkQueue();
        LinkQueue.push(1);
        LinkQueue.push(2);
        LinkQueue.push(3);

        System.out.println("第一个出队的元素:" + LinkQueue.pull());
        LinkQueue.pull();

        System.out.println("队列中的元素:");
        LinkQueue.traverse();

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值