约瑟环求解问题

孩子们的游戏(圆圈中最后剩下的数)

http://www.nowcoder.com/questionTerminal/f78a359491e64a50bce2d89cff857eb6

//利用链表模拟约瑟夫环,来求解该问题;
public class Solution {
public int LastRemaining_Solution(int n, int m) {
CircleList cl= new CircleList();
cl.add(n);
int val=cl.method(n,m);
return val;
}
}

class CircleList{
private ListNode first=null;

public void add(int maxSize){
     ListNode curNode=first;
     for(int i=0;i<maxSize;i++){
         ListNode node= new ListNode(i);
         if(i==0){
             first=node;
             node.next=first;
             curNode=first;
         }else{
             curNode.next=node;
             node.next=first;
             curNode=node;
         }
     }
}

public int getLength(){
    ListNode temp=first;
    int len=1;
    while(temp.next!=first){
        len++;
        temp=temp.next;
    }
    return len;
}
public int method(int n,int m){
    if(m<1 || n<1) return -1;
    ListNode helper=first;
   // ListNode temp=first;
    while(helper.next!=first){
        helper=helper.next;
    }

    while(true){
        for(int i=0;i<m-1;i++){
            first=first.next;
            helper=helper.next;
        }                
            first=first.next;
            helper.next=first;

        if(helper==first){
            break;
        }
    }
    return helper.val;
}

}

class ListNode{
public int val;
public ListNode next;

public ListNode(){

}

public ListNode(int val){
    this.val=val;
}

}

全部评论

相关推荐

02-01 12:05
复旦大学 Java
腾讯的提前批大概率应该是没有笔试的,但是这个时候有相当部分的同学简历估计都没有准备好,没准备好的同学也不用急,大部分都是3月之后开,这个时候开的绝大多数都是神仙打架,问的东西也比较难,打算投递的同学也多看下计算机网络和操作系统,腾讯对这部分的知识问的比较多。另外多刷下牛客的热门题库,刷题注意刷ACM模式,和牛客的周赛题,腾讯有的部门会从这里面出原题。我是@程序员花海关注我,带你了解更多校招资讯!
程序员花海:还没有来得及准备的同学可以看下学习路线:https://www.nowcoder.com/discuss/824693499982315520?sourceSSR=users算法题:https://www.nowcoder.com/feed/main/detail/20e7a999fa04485b88340a274411ca0d?sourceSSR=users八股文:https://www.nowcoder.com/discuss/833102362771251200?sourceSSR=users简历书写方式:https://www.nowcoder.com/discuss/839907820706205696?sourceSSR=users都是以前在牛客发的文章~
软开人,秋招你打算投哪些...
点赞 评论 收藏
分享
2025-12-18 17:10
华南农业大学 Java
哈哈哈,你是老六:感觉算是正常价吧,不是劝退价吧
点赞 评论 收藏
分享
2025-12-15 14:25
云南大学 Java
lei22:入职可能会看学信网,最好别伪装,这个简历找实习肯定是够的,肯定会有收 28 届实习生的公司的,多投就行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务