java 环形链表的约瑟夫问题

news/2025/2/22 19:40:45

牛客题目链接

1. 题目考点

  1. 建立环形单链表
  2. 链表节点的删除
  3. 循环结束条件

2. 考点解析

public int ysf (int n, int m) {
    // write code here
    // 基础:建立带头结点的单链表
    ListNode head = new ListNode(1);
    ListNode r = head;
    for (int i = 2; i <= n; i++) {
        ListNode node = new ListNode(i);
        r.next = node;
        r = node;
    }
    r.next = head;
    // 关键:pre = r
    ListNode p = head, pre = r;
    int i = 0;
    
    // 关键:最后一个节点的性质,p.next == p
    while (p.next != p) {
        i++;
        // 技巧:只需要一个外部的 while 即可,此处的 while 可简化为 if
        if (i == m) {
            pre.next = pnext;
            i = 0;
        }
        pre = p;
        p = pnext;
    }
    return p.val;
}

http://www.niftyadmin.cn/n/897678.html

相关文章

java 链表的奇偶重排

牛客题目链接 1. 题目考点 链表原地划分为两个链表 2. 考点解析 方法一&#xff1a;划分链表 public ListNode oddEvenList (ListNode head) {// write code hereListNode odd new ListNode(0);ListNode even new ListNode(0);ListNode r1 odd, r2 even, p head;whil…

java 重排链表

牛客题目链接 1. 题目考点 找链表中间节点的两种方式翻转链表的两种方式 2. 考点解析 原地构造两个链表 list1 和 list2&#xff0c;list2 采用头插法翻转原链表 public ListNode reorderList(ListNode head) {ListNode l1 new ListNode(0);ListNode l2 new ListNode(0)…

java 字符串最长无重复子串

牛客题目链接 1. 题目考点 HashSet 的使用滑动窗口 set 2. 考点解析 滑动窗口 set public int maxLength (int[] arr) {// write code hereif (arr null || arr.length 0) return 0;Set<Integer> set new HashSet<>();int left 0, right 0, maxLen 0,…

BMP文件格式解析(有调色板)

BMP文件格式详解&#xff08;BMP file format&#xff09; BMP文件格式&#xff0c;又称为Bitmap&#xff08;位图&#xff09;或是DIB(Device-Independent Device&#xff0c;设备无关位图)&#xff0c;是Windows系统中广泛使用的图像文件格式。由于它可以不作任何变换地保存…

java 判断回文

牛客题目链接 1. 题目考点 StringBuilder 判断回文左右比较字符判断回文 2. 考点解析 原始方法&#xff0c;len / 2 public boolean judge (String str) {// write code hereint len str.length();for (int i 0; i < len/2; i) {if (str.charAt(i) ! str.charAt(len-…

BMP文件格式解析(有调色板)2

BMP&#xff08;全称Bitmap&#xff09;是Windows操作系统中的标准图像文件格式&#xff0c;可以分成两类&#xff1a;设备相关位图&#xff08;DDB&#xff09;和设备无关位图&#xff08;DIB&#xff09;&#xff0c;使用非常广。它采用位映射存储格式&#xff0c;除了图像深…

C#调用C或C++编写的DLL库

1.编写DLL文件 &#xff08;1&#xff09;新建DLL工程 &#xff08;2&#xff09;选择空工程&#xff0c;类型为DLL &#xff08;3&#xff09;添加.c文件 #include <stdio.h>struct struStudent {int a;int b;int c; };extern "C" __declspec(dllexport) i…

java 将字符串转化为 整数

牛客题目链接 1. 题目考点 整数溢出判断符号处理 2. 考点解析 分上溢出和下溢出 public int atoi (String str) {// write code hereif (str null || str.length() 0) return 0;// 处理前导空格str str.trim();// 注意&#xff1a;symbol 默认为 1int symbol 1, i 0;…