// An highlighted block
public class MyList {
private MyList next;
private Object data;
public MyList(){};
public MyList(Object data){
this.data=data;
};
public MyList(MyList next,Object data){
this.next=next;
this.data=data;
};
public Object getData() {
return data;
}
public MyList getNext() {
return next;
}
public void setData(Object data) {
this.data = data;
}
public void setNext(MyList next) {
this.next = next;
}
}
下面展示一些 内联代码片
。
链表结构
// An highlighted block
下面展示一些 `内联代码片`。
class MyLinearList {
public MyList source=new MyList();
public int size=0;
public int length() {
return size;
}
public MyLinearList(){super();}
public MyList findKth(int i) {
MyList node = source;
// 计数器,统计当前是第几个结点
int j = 1;
// 循环的条件是结点不能为null并且j必须小于i
while (node != null && j < i) {
node = node.getNext();
j++;
}
// 判断计数器的值是否等于要查询的位序,如果是返回结点否则返回null
if (j == i) {
return node;
} else {
return null;
}
}
public MyList insert(int i, Object data) throws Exception {
// p指的是要插入的位置之前的结点,s指的是要新插入的结点
MyList p, s;
// 如果新结点要插在表头
if (i == 1) {
// 申请新结点
s = new MyList();
// 设置新结点的数据
s.setData(data);
// 处理第一个结点问题
if (size == 0) {
// 设置新节点的指针(下一个结点)的位置
s.setNext(null);
} else {
// 设置新节点的指针(下一个结点)的位置
s.setNext(source);
}
source = s;
size++;
return s;
}
// 查找第(i-1)个结点,即查找要插入的位置的前一个结点
p = findKth(i - 1);
// 判断查询到的结点是否为null
if (p == null) {
throw new Exception("参数i错误!");
} else {
// 申请新结点
s = new MyList();
// 设置新结点的数据
s.setData(data);
// 设置新结点的指针(下一个结点的位置)为查询到的结点的指针
s.setNext(p.getNext());
// 将要插入位置的前一个结点的指针指向当前要添加的新结点
p.setNext(s);
size++;
return source;
}
}
public void print() {
MyList node = source;
while (node != null) {
System.out.print(node.getData() + "\t");
node = node.getNext();
}
System.out.println();
}
}
public class MyGameFrame {
public static void main(String args[]) {
MyLinearList myLinearList=new MyLinearList();
try{myLinearList.insert(1,"2");
myLinearList.insert(1,"1");}
catch (Exception e)
{
e.printStackTrace();
}
myLinearList.print();
}
}