zoukankan      html  css  js  c++  java
  • golang实现简单哈希表(拉链法解决冲突)

    package main
    
    import (
        "fmt"
    )
    
    //可以在初始化时自定义
    const Size =10
    
    type Node struct {
        Val int
        Next *Node
    }
    
    //结构体指针数组
    type Table struct {
        Array []*Node
        //value个数
        Length int
    }
    
    //初始化
    func (n *Table)Init(){
        n.Array = make([]*Node,Size)
        n.Length = 0
    }
    
    //hash值
    func Hash(key int)int  {
        return key%Size
    }
    
    //查找value,没有则返回nil
    func (n*Table)Find(value int)*Node  {
        index:=Hash(value)
        node:=n.Array[index]
        for node!=nil{
            if node.Val==value{
                return node
            }else{
                node = node.Next
            }
        }
        return nil
    }
    
    //添加元素
    func (n*Table)AddValue(value int)bool  {
        node:=n.Find(value)
        //不存在插入,头插法,redis字典也是这样
        if node==nil{
            index:=Hash(value)
            newNode:=new(Node)
            newNode.Val = value
            newNode.Next = n.Array[index]
            n.Array[index] =newNode
            n.Length++
            return true
        }
        node.Val = value
        return true
    }
    
    //删除元素,找到链表位置,去掉节点
    //0 删除成功 -1 失败
    func (n*Table)DelNode(value int)int  {
        index:=Hash(value)
        var cur,pre *Node
        cur = n.Array[index]
        //不空,寻找value
        for cur!=nil{
            if cur.Val==value{
                //index第一个节点value,则index位置为next
                if pre==nil{
                    n.Array[index] = cur.Next
                }else{
                    //非第一个节点,去点节点就可以
                    pre.Next =cur.Next
                }
                //长度减1
                n.Length--
                return 0
            }
            //继续寻找value
            pre = cur
            cur = cur.Next
        }
        //等于nil则无此值
        return -1
    }
    
    //输出哈希表值
    func (n*Table)Print()  {
        for i:=0;i<Size;i++{
            cur:=n.Array[i]
            for cur!=nil{
                fmt.Printf("%v ",cur.Val)
                cur = cur.Next
            }
        }
    }
    
    func main()  {
    
    table:=new(Table)
        table.Init()
        table.AddValue(2)
        table.AddValue(99)
        table.AddValue(3)
        table.Print()
        fmt.Println()
        table.DelNode(2)
        table.Print()
        fmt.Println(table.Find(99))
    }

    没有实现达到一定负载扩容的功能。

  • 相关阅读:
    十六、异步编程——messagedialog
    关于委托的一个摘录
    com interop 简述
    [STAThread]的使用
    Python初识和基础语法
    Python基础数据类型以及格式化输出
    JS读取PHP中设置的中文cookie时出现乱码的解决方法
    解决跨域读写Cookies的问题,(ASP、PHP、ASP.NET、JSP)解决方案
    多字段distinct查询
    Dedecms当前位置{dede:field name='position'/}修改,去掉>方法
  • 原文地址:https://www.cnblogs.com/9527s/p/14222744.html
Copyright © 2011-2022 走看看