题目来源:码蹄集
题目描述:
大概思路:
1.先构建一个长度为n的循环链表,每个节点对应一个人,节点编号从1到n。
2.从节点1开始,按照题目要求依次报数,当报数达到9时,将当前节点从链表中删除。
3.重复步骤2,直到链表中只剩下一个节点,即为幸存者。
4.如果选择的位置恰好是幸存者的位置,则返回该位置的编号;否则,重新构建循环链表,并从第i个节点开始执行步骤1-3,直到找到幸存者。
Python代码实现:
class Node:
def __init__(self, value):
self.value = value
self.next = None
n, m = map(int, input().split())
# 构造循环链表
head = last = Node(1)
for i in range(2, n+1):
node = Node(i)
last.next = node
last = node
last.next = head
i = 1
while head.next != head:
if i == m:
p = head
last.next = head.next
del p
i = 1
head = last.next
else:
last = head
head = head.next
i += 1
print(head.value)
Java代码实现:
import java.util.Scanner;
class Node {
int value;
Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
Node head = null, last = null;
Node node;
for (int i = 0; i < n; i++) {
node = new Node(i + 1, null);
if (i == 0) {
head = node;
last = node;
} else {
last.next = node;
last = node;
}
}
last.next = head;
int i = 1;
while (head.next != head) {
if (i == m) {
Node p = head;
last.next = head.next;
i = 1;
head = last.next;
p = null; // 释放节点内存
} else {
last = head;
head = head.next;
i++;
}
}
System.out.println(head.value);
}
}
C++代码实现:
参考链接:https://blog.csdn.net/matiji2008/article/details/126072827
#include <iostream>
#include <stdio.h>
#include <memory>
typedef struct NODE{
int value;
NODE *next;
} NodeList;
int main() {
int n, m;
scanf("%d %d", &n, &m);
NodeList *head, *last = NULL;
NodeList *node;
for(int i=0; i<n; ++i){
node = (NodeList*)malloc(sizeof(NodeList));
node->value = i+1;
if(i == 0){
head = node;
last = node;
}else{
last -> next = node;
last = node;
}
}
node->next = head;
last = node;
int i = 1;
while(head->next != head){
if(i == m){
NodeList *p = head;
last->next = head->next;
free(p);
i = 1;
head = last->next;
}else{
last = head;
head = head->next;
++i;
}
}
printf("%d\n", head->value);
return 0;
}
代码提交测试结果:
附B站老师讲解链接:https://www.bilibili.com/video/BV1Ua4y1V7qX/?t=2324.0