m個人圍成一圈,每隔n個人出列,求出列的順序
阿新 • • 發佈:2019-01-01
#include<iostream.h>
#include <string.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
node *next;
}Node;
int func(int m,int n){
int i=0,j=0;
Node *head,*p,*q;
head=(Node *)malloc(sizeof(Node));
q=head;
if(head!=NULL){
head->next=head;
head->data=0;
}else{
printf("head is null\n");
return 0;
}
for(i=1;i<m;i++){
p=(Node *)malloc(sizeof(Node));
if(p!=NULL){
p->data=i;
p->next=q->next;
q->next=p;
q=p;
}else{
printf("p is null\n");
return 0;
}
}
p=head;
q=head;
while(p->next!=p){
if(j==n){
q->next=p->next;
printf("%d out\n",p->data);
free(p);
p=q->next;
j=0;
}else{
q=p;
p=p->next;
j++;
}
}
printf("%d is last\n",p->data);
return 1;
}
int main(void) {
int result=func(10,3);
if(result==0){
printf("error\n");
}else{
printf("success\n");
}
return 0;
}
#include <string.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
node *next;
}Node;
int func(int m,int n){
int i=0,j=0;
Node *head,*p,*q;
head=(Node *)malloc(sizeof(Node));
q=head;
if(head!=NULL){
head->next=head;
head->data=0;
}else{
printf("head is null\n");
return 0;
}
for(i=1;i<m;i++){
p=(Node *)malloc(sizeof(Node));
if(p!=NULL){
p->data=i;
p->next=q->next;
q->next=p;
q=p;
}else{
printf("p is null\n");
return 0;
}
}
p=head;
q=head;
while(p->next!=p){
if(j==n){
q->next=p->next;
printf("%d out\n",p->data);
free(p);
p=q->next;
j=0;
}else{
q=p;
p=p->next;
j++;
}
}
printf("%d is last\n",p->data);
return 1;
}
int main(void) {
int result=func(10,3);
if(result==0){
printf("error\n");
}else{
printf("success\n");
}
return 0;
}