约瑟夫问题与循环链表(Java日记Ⅴ)

这篇博客讨论了一个在循环链表中删除指定位置元素的程序实现。代码中特别处理了begin_index等于1的情况,并指出可能存在优化空间,但由于时间限制未进行重构。程序包括创建链表、遍历链表、获取链表长度以及删除元素等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总的来说没有太大难度,主要是当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);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值