以单链表为底层创建自己的容器
//单链表
public class MySingleList {
//1.创建结点
class Node {
Object data;//存储的信息
Node next;
public Node(Object data, Node next) {//构造方法:初始化一个新的结点
this.next = next;
this.data = data;
}
}
//单链表的头结点与元素个数
private Node first;//头结点
private int total;//有效个数
//1.增
public void add(Object obj){
//首先判断链表是否为空
if (first==null){//如果是空的,将头结点的信息域为obj
first=new Node(obj,null);
}else{
Node now=first;
while(now.next!=null){
now=now.next;
}
now.next=new Node(obj,null);
}
total++;//添加过后记得total++
}
//2.删
public void remove(Object obj){
//首先判断是否为空 在判断是否为第一个
if (obj==null){
if (first.data==null){
first=first.next;
}else {//删除元素不在第一个结点
Node just=first;
Node now=first.next;
while (now.data!=obj){
just=now;
now=now.next;
}
just.next=now.next;
}
}else {
if (obj.equals(first.data)){
first=first.next;
}else {
Node just=first;
Node now=first.next;
while (!obj.equals(now.data)){
just=now;
now=now.next;
}
just.next=now.next;
}
}
total--;
}
//有效结点个数
public int size(){
return total;
}
//查看元素
public Object[] toArray(){
Object all[]=new Object[total];
Node node=first;
for (int i = 0; i < all.length; i++) {
//给数组赋值
all[i]=node.data;
node=node.next;
}
return all;
}
}
测试类:
public class TestMySingleList {
public static void main(String[] args) {
MySingleList ms=new MySingleList();
ms.add(123);
ms.add(456);
ms.add(789);
ms.add(null);
ms.add(456789);
ms.add(789456);
ms.remove(null);
Object all[]=ms.toArray();
for (int i = 0; i < all.length; i++) {
System.out.println(all[i]);
}
System.out.println(ms.size());
}
}
感谢段段