参考学习网站: www.mayikt.com
hashMap在发生hashcode冲突的时候,在数组中使用链表,并且冲突的元素添加到链表头,简称 头插法。
package com.mayikt.linkedlist;
/**
* 单向链表
*
* @author zx
* @date 2022年01月28日 16:10
*/
public class SingleLinkedList<T> {
/**
* 头结点
*/
transient Node<T> firstNode;
/**
* 链表结点个数
*/
int size = 0;
/**
* 把元素添加到链表的头结点
*
* @param t 添加的元素
* @return true表示添加成功
*/
public boolean add(T t) {
addNodeToHead(t);
return true;
}
private void addNodeToHead(T t) {
Node<T> tempNode = firstNode;
firstNode = new Node<>(t, tempNode);
size++;
}
public void showInfo() {
Node<T> temp = firstNode;
while (true) {
System.out.println(temp.item);
if (temp.nextEntry == null) {
//链表遍历到最后了
break;
}
temp = temp.nextEntry;
}
}
static class Node<T> {
T item;
Node<T> nextEntry;
public Node(T item, Node<T> nextEntry) {
this.item = item;
this.nextEntry = nextEntry;
}
}
public static void main(String[] args) {
SingleLinkedList<String> singleLinkedList = new SingleLinkedList<>();
singleLinkedList.add("I");
singleLinkedList.add("LOVE");
singleLinkedList.add("YOU");
singleLinkedList.showInfo();
}
}