总的来说没有太大难度,主要是当begin_index和count为一时程序容易出问题,要单独处理,另外我这里first在后cur在前,当begin_index为一时要单独处理first让它指向cur的前一位,代码写的不是特别满意,感觉有些地方可以简化,奈何今天事情太多,没时间重构了,就这样吧,毕竟也不是什么大问题。
代码如下:
public class YSFQuestion {
public static void main(String[] args) {
CircleLinkList lst=new CircleLinkList(5);
lst.sayHello();
lst.circleTick(1,2);
}
}
class CircleLinkNode{
int id;
CircleLinkNode next;
public CircleLinkNode(int id){
this.id=id;
}
public void sayHello(){
System.out.println("my id is "+id);
}
}
class CircleLinkList{
CircleLinkNode first=new CircleLinkNode(1);
public CircleLinkList(int n){
if(n<1){
System.out.println("请输入一个大于等于1的数");
return;
}
for (int i = 1; i <= n; i++) {
if(i==1){
first.next=first;
}
else {
CircleLinkNode node=new CircleLinkNode(i);
CircleLinkNode cur=first;
while (cur.next!=first){
cur=cur.next;
}
cur.next=node;
node.next=first;
}
}
}
public void sayHello(){
CircleLinkNode cur=first;
while (cur.next!=first){
cur.sayHello();
cur=cur.next;
}
cur.sayHello();
}
public int length(){
CircleLinkNode cur=first;
int count=1;
while (cur.next!=first){
cur=cur.next;
count++;
}
return count;
}
public void circleTick(int begin_index ,int count){
int len=length();
if(begin_index>len||begin_index<1){
System.out.println("起始位置有误,链表最大长度为"+len);
return;
}
CircleLinkNode cur=first;
if(begin_index==1){
while (first.next!=cur){
first=first.next;
}
}
while (begin_index!=1){
first=cur;
cur=cur.next;
begin_index--;
}
int n=count;
while (cur.next!=cur) {
while (count!=1){
first=cur;
cur=cur.next;
count--;
}
first.next=cur.next;
System.out.println("踢出 id "+cur.id);
cur=first.next;
count=n;
}
cur.next=null;
System.out.println("踢出 id "+cur.id);
}
}