单向循环链表解决:joseph问题?
作者:互联网
设编号分别为:1,2,…,n的n个人围坐一圈。约定序号为k(1≤k≤n)的人从1开始计数,数到m(m>=1)的那个人出列,他的下一位又从1开始计数,数到m的那个人又出列,依次类推,直到所有人出列为止,求出列顺序
例如:n=8,k=3,m=4时,出列序列为:(6,2,7,4,3,5,1,8)
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node{
datatype data;
struct node *next;
//looplist *next; //错误写法。C语言从上往下执行的
}looplist; //不知道looplist 是什么。
//创建有头单向循环链表函数
looplist * createlooplist()
{
looplist *s =(looplist *)malloc(sizeof(looplist));
s->next = s;
return s;
}
//头插法插入操作
void looplistInsertHead(looplist *s,datatype value){
looplist *temp = (looplist *)malloc(sizeof(looplist));
temp->data = value;
temp->next = s->next;
s->next = temp;
}
//去头操作
looplist * looplistCutHead(looplist *s){
looplist *temp = s;
while(s->next!=temp){
s = s->next;
}
s->next = temp->next;
free(temp);
temp =NULL;
return s->next;
}
//无头链表打印
void looplistCutHeadPrintf(looplist *s){
looplist *p = s;
while(s->next !=p){
printf("%5d",s->data);
s=s->next;
}
printf("%5d\n",s->data);
}
//有头链表打印
void looplistPrintf(looplist *s){
looplist *p = s;
while(s->next !=p){
s=s->next;
printf("%5d",s->data);
}
puts("");
}
int main(int argc, const char *argv[])
{
int k = 3,m=4;
int i = 8;
//创建有头单向循环链表
looplist *h =createlooplist();
for(i;i>=1;i--){
looplistInsertHead(h,i);
}
looplistPrintf(h);
//去掉头操作,变成无头单向循环链表
h=looplistCutHead(h);
//looplistCutHeadPrintf(h);
//找到第三个人
for(i=1;i<k;i++){
h = h->next;
}
//循环找到数到m的人,并将其从链表中删除
//循环条件就是剩下最后一个人
looplist *temp;
while(h->next!=h){
for(i=1;i<m-1;i++){
h = h->next;
}
temp = h->next;
h->next = temp->next;
printf("%5d",temp->data);
free(temp);
temp =NULL;
h = h->next;
}
printf("%5d\n",h->data);
free(h);
return 0;
}
标签:looplist,temp,int,单向,next,链表,joseph,data 来源: https://blog.csdn.net/YuHangAndYaNan/article/details/123597019