日期:2014-05-20 浏览次数:21197 次
public class TestCount {
public static void main(String[] args) {
kidCicrle kc = new kidCicrle(20);
int countNum = 0;
kid k = kc.first;
while (kc.count>0&&k!=null){//加k!=null约束
countNum++;
if (countNum == 3){
countNum = 0;
kc.delete(k);
}
k = k.son;
}
for(kid k1 = kc.first;k1 != null;k1 = k1.son){//链表遍历
System.out.print(k1.id +" ");
}
}
}
class kid {
int id = 0;
kid father = null;
kid son = null;
}
class kidCicrle {
int count = 0;
kid first = null;
kid last = null;
kidCicrle(int n) {
for (int i = 0;i<n;i++){//你赋值为0,对照你自己的程序
add();
}
}
void add() {
kid k = new kid();
k.id = count;
if (count==0){
first=k;
last=k;
first.son = last;
last.father = first;
}
else{
k.father = last;//注意双向都要连,避免照成空指针异常
last.son = k;
last = k;
}
count++;
}
void delete(kid k){
if (count <= 0){
System.out.println("error");
}else if (count==1){
first = null;
last = null;
}else {//双向链表,把引用搞清楚。
if (k==first){
k.son.father = null;
first = k.son;
}
else if (k==last){
k.father.son=null;
last = k.father;
}
else{
k.son.father = k.father;
k.father.son = k.son;
}
}
count--;
}
}