//定义一个链表类,与其它类一样,包括成员变量和成员函数等。
//成员变量可以是对象的引用,成员函数包括通过构造函数对变量赋值,也包括通过一般的方法为成员函数赋值或者是返回变量值。
public class SingleListElem
{
//fields
protected Object data; //变量定义为Object类型,说明data可以是对象的引用。可以给它赋值为一个对象。
protected SingleListElem nextElem; //指向下一个链表元素,注意其数据类型就是本类名。
//constructor 构造函数,给变量赋初值。
public SingleListElem(Object data, SingleListElem next)
{
this.data = data;
this.nextElem = next;
}
//构造函数重载,如果对象无下一链表,则将nextElem值空。
public SingleListElem(Object data)
{
SingleListElem(data, null);
}
//non-static method
//通过一个函数为成员变量nextElem赋值,也就是赋下一个链接元素的引用。
public void setNext(SingleListElem next)
{
nextElem = next;
}
//通过函数返回成员变量值,在这里也就是返回对象的引用。
public Object value()
{
return data;
}
//通过函数为对象的引用赋值。
public void setValue(Object value)
{
data = value;
}
}
//定义一个类,用于对链表进行操作,比如增加一个头元素、增加一个尾元素、删除一个尾元素等
public class SingleList
{
//field
protected long count; //用以记录链表元素的序列
protected SingleListElem head;//定义一个链表的头元素,引用链表的时候只需要从头元素开始,将头元素作为参数传给引用的函数。
//constructor构造函数,先赋初值。
public SingleList()
{
head = null;
count = 0;
}
//return size
public long size()
{
return count;
}
//上下为什么写两个函数,直接写count==0不好吗?
public boolean isEmpty()
{
return size()==0;
}
//add element to head 产生第一个链表元素,增加头元素
public void addToHead(Object value)
{
//用的是第一种构造方法,其实可以用第二种构造方法的,将第一个链表对象的引用值赋给head
head = new SingleListElem(value, head);
count++;
}
//remove element from head 移走头元素
public Object removeFromHead()
{
SingleListElem tmp = head;
head = head.next();
count--;
return tmp;
}
//add element to tail 链表尾增加一个元素
public void addToTail(Object value)
{
SingleListElem tmp = new SingleListElem(value,null);
if(head!=null) //如果第一个元素存在
{
SingleListElem pointor = head; //从第一个元素开始循环
while(pointor.next()!=null) //只要链表中有元素存在,则向下找,直到最后一个元素的下一个引用被得到
{
pointor = pointor.next();
}
pointor.setNext(tmp);//将新对象赋值给引用变量
}
else
{head = tmp;}
count++;
}
//remove from tail删除尾元素
public Object removeFromTail()
{
SingleListElem pointor = head;//注意,都是从头开始找起的
SingleListElem pre = null;
while(pointor.next()!=null) {
pre = pointor;
pointor = pointor.next();
}
if(pre == null) head = null;
else pre.setNext(null);
count--;
return pointor.value;
}
public clear()
{
head = null;
count = 0;
}
//and other method such as contains, remove, toString...
//I think it is easy for you ,hehe
}