1.创建单链表的结点Node类
/**
* 单链表的结点
* @author Administrator
*/
public class Node {
/**
* 要存储的数据
*/
private Object data;
/**
* 后继
*/
private Node next;
public Node(Object data) {
this.data = data;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
", next=" + next +
'}';
}
}
2.单链表结构的实现类(SingleLinkedList)
/**
* 单链表
* @author Administrator
*/
public class SingleLinkedList implements List {
/**
* 头结点,不存储数据,为了编程方便
*/
private Node head = new Node(null);
/**
* 一共几个结点
*/
private int size;
/**
* 定义size方法,应返回size大小,最大值为Integer.MAX_VALUE
*
* @return
*/
@Override
public int size() {
return size;
}
/**
* List要求,定义get方法,获取指定index的值
*
* @param index
* @return
*/
@Override
public Object get(int index) {
//如果index位置错误,抛异常
if (index<0 || index>=size){
throw new MyArrayIndexOutOfBoundsException("数组越界异常:"+index);
}
//和顺序表不一样,不能通过索引直接计算定位,需要从头结点开始查找
Node p = getNode(index);
return p.getData();
}
/**
* 定义isEmpty方法,用于返回是否为空
* 如果不包含元素,则返回true
*
* @return
*/
@Override
public boolean isEmpty() {
return size==0;
}
/**
* 定义conta