class MyList<T> {
private int size = 0;
// 头节点
Node first = null;
// 尾节点
Node last = null;
// 链表节点类(内部类)
// 插入链表节点的方法
// 参数i : 表示要插入的位置,当 i = -1 时新节点会被放置头位置,若 i = -2 时新节点会被放置至尾位置
public void add(T data /* 传入数据 */) {
// 创建新节点
Node newNode = new Node();
newNode.data = data;
newNode.next = null;
// 一个元素都没有
if (this.last == null) { //没有元素
this.first = newNode;
this.last = newNode;
} else { // 链表里有元素,在末尾新增一个
this.last.next = newNode;
this.last = newNode;
}
this.size++;
}
public void addList(MyList list) {
if (list.size == 0) {
return;
}
// 一个元素都没有
if (this.last == null) { //没有元素
this.first = list.first;
this.last = list.last;
} else { // 有元素
this.last.next = list.first;
this.last = list.last;
}
this.size += list.size;
}
public void clear() {
this.first = null;
this.last = null;
this.size = 0;
}
}
class Node {
// 下一个节点
Node next;
// 数据块
Object data;
}
java链表模板
最新推荐文章于 2024-10-05 12:07:50 发布