用单链表结构实现一个Map

tech2023-11-23  83

public class LinkListMap<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() { this(null,null,null); } public Node(K key) { this(key,null,null); } @Override public String toString() { return key.toString() + ":" + value.toString(); } } //定义节点 private Node dummyHead; //定义Map长度 private int size; //初始化 节点 和 长度 public LinkListMap(){ dummyHead = new Node(); size = 0; } //根据key 获取 Node节点 private Node getNode(K key){ Node cur = dummyHead.next; while (cur != null){ if (cur.key.equals(key)){ return cur; } cur = cur.next; } return null; } //根据key 获取 Value private V getValue(K key){ Node cur = dummyHead.next; while (cur != null){ if (cur.key.equals(key)){ return cur.value; } cur = cur.next; } return null; } //添加一对键-值 public void put(K key, V value) { Node node = getNode(key); if (node == null) { dummyHead.next = new Node(key,value,dummyHead.next); size++; }else { node.value = value; } } //根据key删除一对键-值 public void remove(K key) { Node prv = dummyHead; while (prv.next!=null) { if(prv.next.key.equals(key)){ break; } prv=prv.next; } if(prv.next!=null){ Node delNode = prv.next; prv.next = delNode.next; delNode.next = null; size--; } } public String toString() { StringBuffer str = new StringBuffer(""); Node node = dummyHead.next; while (node != null) { str.append(node + "\n"); node = node.next; } return str.toString(); } public static void main(String[] args) { LinkListMap<String,String> map = new LinkListMap<String,String>(); map.put("1", "zhangsan"); map.put("2", "lisi"); map.put("3", "wangwu"); map.put("4", "xiaoliu"); System.out.println(map.toString()); System.out.println(map.size); System.out.println("-----------"); map.remove("3"); System.out.println(map.toString()); System.out.println(map.size); System.out.println("-----------"); map.put("3", "wangwu"); System.out.println(map.toString()); System.out.println(map.size); System.out.println("-----------"); System.out.println(map.getValue("3")); } }
最新回复(0)