本文参考LinkedList源码实现单链集合的实现,如果想了解双链实现,请参考点击打开链接
接口:
public interface MyList {
/**
* 定义添加接口
* @param element
*/
public void add(T element);
/**
* 定义clear接口
*/
public void clear();
/**
* 删除接口
* @param index
* @return
*/
public boolean remove(int index);
/**
* 查找,判断对象是否存在
* @param element
* @return
*/
public boolean find(T element);
/**
* 根绝索引查找
* @param index
* @return
*/
public T get(int index);
/**
* 获取当前的链表的个数
* @return
*/
public int size();
}存储数据 data实体类:
public class Node {
//数据
private T data;
//下一个节点的对象
private Node next;
public Node() {
data = null;
next = null;
}
public Node(T data) {
this.data = data;
this.next = null;
}
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
public void setData(T data) {
this.data = data;
}
public T getData() {
return this.data;
}
public void setNext(Node next) {
this.next = next;
}
public Node getNext() {
return this.next;
}
}
实现类:
public class MyLinkedList implements MyList {
//存储节点
private Node head;
//存储每一个当前的节点
private Node tail;
//存储当前链表的size
private int size;
public MyLinkedList() {
this.head = null;
this.tail = null;
this.size = 0;
}
public MyLinkedList(T data) {
this.head = new Node(data);
this.tail = null;
this.size = 0;
}
@Override
// 添加元素
public void add(T element) {
//生成当前节点的对象
Node node = new Node(element);
//首次操作将两个存储对象指向同一个内存空间
if (this.head == null) {
this.head = node;
this.tail = node;
} else {
//将新的note节点指向tail节点(head的尾端节点)
this.tail.setNext(node);
//将note节点重新赋值给tail,tail就会变成head的最后一个节点
this.tail = node;
}
this.size++;
}
@Override
// 清空链表
public void clear() {
this.head = null;
this.tail = null;
System.gc();//清除内存
}
/**
* 获取元素
*/
@Override
public T get(int index) {
T t = null;
//index不超过size的限制
if (index >= 0 && index < size) {
Node point = head;
int count = 0;
//循环找到所在的节点
while (count < size) {
if (count == index) {
t = point.getData();
break;
}
point = point.getNext();
count++;
}
}
return t;
}
@Override
/**
* 删除元素
* @param index
* @return
*/
public boolean remove(int index) {
if (index >= 0 && index < size) {
Node point = head;
int count = 0;
// 当对象是最后一个的时候
while (count < size) {
if (count == index) {
break;
}
point = point.getNext();
count++;
}
Node temp = point.getNext(); //获取下一个节点的数据
//替换当前的节点
point.setData(temp.getData());
//替换下一个节点
point.setNext(temp.getNext());
temp = null;
size--;
return true;
}
return false;
}
@Override
// 查找链表中是否包含某元素
public boolean find(T element) {
Node point = head;
while (point.getNext() != null) {
if (point.getData().equals(element)) {
return true;
}
point = point.getNext();
}
return false;
}
@Override
public int size() {
return this.size;
}
}