栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

初始数据结构之符号表

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

初始数据结构之符号表

符号表
  • 结构

键值对,仅此而已,一个key一个value组成,下边演示的是通过链表形式实现的符号表。并且符号表要求key唯一。

  • 自己实现符号表抽象类
public abstract class SymbolTable {

    // 头部节点
    protected Node headNode;
    // 符号表元素个数
    protected int size;

    public SymbolTable() {
        this.headNode = new Node<>(null, null, null);
        this.size = 0;
    }

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

    
    public V get(K key) {
        Node temp = this.headNode;
        while (temp.next != null) {
            temp = temp.next;
            if (temp.key.equals(key)) {
                return temp.value;
            }
        }
        return null;
    }

    
    public abstract void put(K key, V value);

    
    public void delete(K key) {
        Node preNode = this.headNode;
        Node currentNode;
        while (preNode.next != null) {
            currentNode = preNode.next;
            if (currentNode.key.equals(key)) {
                preNode.next = currentNode.next;
                this.size --;
                return ;
            }
            preNode = currentNode;
        }
    }


    
    class Node {
        K key;
        V value;
        Node next;

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
}

无序符号表
  • 特点

元素的插入没有顺序,通常新增元素为直接插入在头节点之后。

  • 自己实现无序符号表
public class NormalSymbolTable extends SymbolTable {

    
    public void put(K key, V value) {
        Node temp = this.headNode;
        // 确定key的唯一性,key存在就进行值的替换
        while (temp.next != null) {
            temp = temp.next;
            if (temp.key.equals(key)) {
                temp.value = value;
                return ;
            }
        }
        // key不存在,就从头部新增一个节点
        temp = this.headNode.next;
        Node currentNode = new Node(key, value, temp);
        this.headNode.next = currentNode;
        this.size ++;
    }
}
有序符号表
  • 特点

元素插入时是按照key的顺序进行放置的。

  • 自己实现有序符号表
public class OrderSymbolTable, V> extends SymbolTable{

    
    @Override
    public void put(K key, V value) {
        Node preNode = this.headNode;
        Node currentNode = this.headNode.next;
        while (currentNode != null) {
            if (key.compareTo(currentNode.key) < 0) break;
            if (currentNode.key.equals(key)) {
                currentNode.value = value;
                return;
            }
            preNode = currentNode;
            currentNode = currentNode.next;
        }
        Node newNode = new Node(key, value, currentNode);
        preNode.next = newNode;
        this.size ++;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/860567.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号