剑指offer——孩子们的游戏

xiaoxiao2021-02-28  111

有一个有n个人的圆圈,n个人的编号是0-n-1,这n个人从第0个人开始报数,报数到第m-1个人的时候,将第m-1个人踢出圆圈,然后从它下面的这个人重新开始报数

我是用循环链表实现的,初学编程的时候看到链表、指针就怂,现在手到擒来,还是很开心的

public class Solution { public int LastRemaining_Solution(int n, int m) { if(m < 0) return -1; if(n == 0) return -1; if(n == 1 )return 0; ListNode head = new ListNode(); head.pos = 0; ListNode t = head; for(int i = 1; i < n; ++i) { ListNode listNode = new ListNode(); t.after = listNode; listNode.before = t; listNode.pos = i; t = t.after; if(i == n-1) { listNode.after = head; head.before = listNode; } } int cnt = -1; while (head.before != head && head.after != head) { ++cnt; if(cnt == m-1) { head.before.after = head.after; head.after.before = head.before; //System.out.println("删掉" + " " + head.pos + " 结点"); head = head.after; cnt = -1; } else { head = head.after; } } return head.pos; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.LastRemaining_Solution(6, 7)); } } class ListNode { ListNode before; ListNode after; int pos; }
转载请注明原文地址: https://www.6miu.com/read-48046.html

最新回复(0)