环形链表的约瑟夫问题

牛客地址

解题思路

import java.util.*;


public class Solution {
    /**
     * 
     * @param n int整型 
     * @param m int整型 
     * @return int整型
     */
    class Ring{
        class RingNode{
            int val;
            RingNode next;
            public RingNode(int val){
                this.val = val;
            }
        }
        RingNode head = null;
        RingNode tail = null;
        public void add(int val){
            if(head == null){
                head = new RingNode(val);
                head.next = head;
                tail = head;
            }
            else{
                tail.next = new RingNode(val);
                tail = tail.next;
                tail.next = head;
            }
        }
        public int delete(int m){
            if(m == 1){
                return tail.val;
            }
            //只剩下一个节点
            if(head.next == head){
                return head.val;
            }
            RingNode curPre = null;
            RingNode cur = head;
            for(int i = 1; i < m; i++){
                curPre = cur;
                cur = cur.next;
            }
            //cur为待删除的节点
            //如果删除的是头节点
            if(cur == head){
                tail.next = head.next;
                head = tail.next;
            }
            //如果删除的是尾节点
            else if(cur == tail){
                tail = curPre;
                tail.next = head;
            }
            else{
                head = cur.next;
                tail = curPre;
                curPre.next = cur.next;
            }
            return -1;
        }
    }
    public int ysf (int n, int m) {
        // write code here
        Ring ring = new Ring();
        for(int i = 1; i <= n; i ++){
            ring.add(i);
        }
        int res = -1;
        while(true){
            res = ring.delete(m);
            if(res != -1){
                break;
            }
        }
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值