环形链表的约瑟夫环

环形链表的约瑟夫问题

http://www.nowcoder.com/questionTerminal/41c399fdb6004b31a6cbb047c641ed8a

根据题意,正常构造链表满足条件删除即可
别投机取巧,自己手打一遍熟悉熟悉

import java.util.*;


public class Solution {
    /**
     * 
     * @param n int整型 
     * @param m int整型 
     * @return int整型
     */

    public int ysf (int n, int m) {
        // write code here
        ListNode head=new ListNode(1);
        ListNode tail=head;
        for(int i=2;i<=n;i++){
            tail.next=new ListNode(i);
            tail=tail.next;
        }
        tail.next=head;
        ListNode index=head;
        ListNode pre=tail;
        int k=0;
        while(index.next!=null&&index.next!=index){
            k++;
            ListNode next=index.next;
            if(k==m){
                pre.next=pre.next.next;
                k=0;
            }
            pre=index;
            index=next;
        }
        return index.val;
    }
}
全部评论
步长为1的案例都无法通过
1 回复 分享
发布于 2021-10-08 08:50
你这有问题 试一下 3 1
点赞 回复 分享
发布于 2021-12-26 10:28
public int ysf (int n, int m) { // write code here ListNode head=new ListNode(1); ListNode tail=head; for(int i=2;i<=n;i++){ tail.next=new ListNode(i); tail=tail.next; } tail.next=head; ListNode index=head; ListNode pre=tail; int k=0; while(index.next!=null&&index.next!=index){ k++; ListNode next=index.next; if(k==m){ pre.next=pre.next.next; k=0; index = next; } else { pre = index; index = next; } } return index.val; }
点赞 回复 分享
发布于 2021-10-23 17:29

相关推荐

仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
22
1
分享

创作者周榜

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