题目:
用循环链表实现:N个乘客同乘一艘船,因为严重超载,加上风高浪大,危险万分,因此船长告诉乘客,只有将部分乘客投入海中,其余人才能幸免于难。
无奈,大家只得同意这种办法。于是N个人围成一圈(从1,2,3...N分别编号)。由编号为1的人开始,依次报数,数到第M人,便把他投入大海中,
然后再从他的下一个人数起,数到第M人,再将他扔到大海中,如此循环地进行,直到剩下K个乘客为止。按顺序依次输出被扔下大海的乘客的编号。
提交格式:
实现int * solve(int N,int M,int K)函数。
函数参数为乘客人数N、间隔人数M和剩余乘客人数K,1<=N<=1000,1<=M<=500000,0<=K<N。
函数返回值为按顺序被扔下大海乘客编号的数组。
请不要printf输出任何内容。
输入样例1:
9 3 2
输出样例1:
3 6 9 4 8 5 2
输入样例2:
12 5 6
输出样例2:
5 10 3 9 4 12
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct Node {
int data;
Node* before;
Node* next;
}Node;
int * solve(int N,int M,int K){
int *res=(int *)malloc((N-K)*sizeof(int));
Node* head=new Node();
head->next=head;
head->data=1;
Node *tail = head;
for(int i=0;i<N-1;i++){
Node *new_node=new Node();
new_node->data=i+2;
new_node->next=head;
new_node->before=tail;
tail->next=new_node;
tail=new_node;
}
head->before=tail;
Node *current=head;
int count;int r=0;
int n=N,p=1;
while(N!=K){
count=1;
if(count==M) {
res[r++]=current->data;
current->next->before=current->before;
current->before->next=current->next;
current=current->next;
N--;
continue;
}
while(count<M){
current=current->next;
count++;
}
res[r++]=current->data;
current->next->before=current->before;
current->before->next=current->next;
N--;
current=current->next;
}
return res;
}
使用双向循环链表解决,注意M==1的情况要单拎出来