用c++循环链表实现约瑟夫环
时间: 2023-05-31 12:02:37 浏览: 122
数据结构 用双向链表实现约瑟夫环
```
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int num;
struct node *next;
}Node;
Node *create(int n){
Node *head = (Node *)malloc(sizeof(Node));
head->num = 1;
head->next = NULL;
Node *tail = head;
int i;
for(i=2;i<=n;i++){
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->num = i;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
tail->next = head; //构成循环链表
return head;
}
void run(Node *head, int m, int k){
Node *p = head;
Node *pre = head;
while(p->next != p){ //当链表中只有一个结点时,退出循环
int i;
for(i=0;i<m-1;i++){ //找到要删除的结点
pre = p;
p = p->next;
}
if(p->num == k){ //找到要删除的结点
printf("%d ",p->num); //输出被删除的结点的编号
pre->next = p->next; //从链表中删除该结点
free(p);
p = pre->next; //p指向下一个结点
}
else{
pre = p; //p不是要删除的结点,pre指向p,p指向下一个结点
p = p->next;
}
}
printf("%d\n",p->num); //输出链表中剩余的最后一个结点
}
int main(){
int n,m,k;
printf("请输入人数n,报数m,要删除的编号k:");
scanf("%d %d %d",&n,&m,&k);
Node *head = create(n);
run(head,m,k);
return 0;
}
```
阅读全文