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
;
private int size
;
public LinkListMap(){
dummyHead
= new Node();
size
= 0;
}
private Node
getNode(K key
){
Node cur
= dummyHead
.next
;
while (cur
!= null
){
if (cur
.key
.equals(key
)){
return cur
;
}
cur
= cur
.next
;
}
return null
;
}
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
;
}
}
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"));
}
}
转载请注明原文地址:https://tech.qufami.com/read-13906.html