java——链表映射 LinkedListMap

好像也不是基于链表来实现的,而是采用与链表类似的节点形式重新定义了一个节点内部类,以此来实现映射

public class LinkedListMap<K, V> implements Map<K, V> {
    
    private class Node{
        public K key;
        public V value;
        public Node next;
        
        public Node(K key,V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
        public Node(K key) {
            this(key, null, null);
        }
        public Node() {
            this(null, null, null);
        }
        
        @Override
        public String toString() {
            return key.toString() + " : " + value.toString();
        }
    }
    
    private Node dummyHead;
    private int size;

    private Node getNode(K key) {
        Node cur = dummyHead.next;
        while(cur != null) {
            if(cur.key.equals(key)) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }
    
    @Override
    public void add(K key, V value) {
        //key具有唯一性
        Node node = getNode(key);
        if(node == null) {
            //??????????
            dummyHead.next = new Node(key, value, dummyHead.next);
            size ++;
        }else {
            node.value = value;
        }
        
    }

    @Override
    public V remove(K key) {
        Node prev = dummyHead;
        while(prev.next != null) {
            if(prev.next.key.equals(key)) {
                break;
            }
            prev = prev.next;
        }
        if(prev.next != null) {
            Node cur = prev.next;
            prev.next = cur.next;
            cur.next = null;
            size --;
            return cur.value;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        // TODO Auto-generated method stub
        return getNode(key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node == null ? null : node.value;
    }

    @Override
    public void set(K key, V newValue) {
        Node node = getNode(key);
        if(node == null)
            throw new IllegalArgumentException(key + "doesn't exist!");
        node.value = newValue;
    }

    @Override
    public int getSize() {
        // TODO Auto-generated method stub
        return size;
    }

    @Override
    public boolean inEmpty() {
        // TODO Auto-generated method stub
        return size == 0;
    }
    
    
}

 

posted @ 2018-10-28 18:17  高圈圈  阅读(929)  评论(0编辑  收藏  举报