正好之前写过基础的约瑟夫环,稍作修改就可以满足你的题目
#include <stdio.h>#include <stdlib.h>
typedef struct _node {
int id
int key
struct _node *next
} Linklist
int main() {
int n, m
scanf("%d %d", &n, &m)
int i, count = 0
Linklist *head = (Linklist*)malloc(sizeof(Linklist)), *tail = head
head->id = 1
scanf("%d", &head->key)
head->next = head
for(i = 2 i <= n i++) {
Linklist *p = (Linklist*)malloc(sizeof(Linklist))
p->id = i
scanf("%d", &p->key)
p->next = head
tail->next = p
tail = p
}
while(head != tail) {
if(++count % m) {
tail = head
} else {
m = head->key
count = 0
printf("%d ", head->id)
tail->next = head->next
free(head)
}
head = tail->next
}
printf("%d\n", head->id)
free(head)
return 0
}
#include<stdio.h>struct
list//建立一个结构体,包括每个人的编号,密码和下一级的指针
{
int
id
int
code
struct
list
*next
}
typedef
struct
list
list//把结构体用list表示
list*
input(int
n)//链表的初始化
{
list
*p,*q,*l
int
i,m
p=new
list
l=new
list
l->next=NULL
p=l
p->id=1//第一个人的初始化
scanf("%d",&m)
p->code=m
for(i=2i<=ni++)//第二个人到第num个人的初始化
{
q=new
list
q->id=i
scanf("%d",&m)
q->code=m
q->next=NULL
p->next=q
p=q
}
p->next=l//使表尾指向表头,成循环链表
return
p
}
int
main()
{
int
num,m1,i
list
*q,*p
while(scanf("%d",&num)!=EOF)
{
printf("第一次的密码为:")
scanf("%d",&m1)
p=input(num)
//printf("%4d\n",head->id)
printf("出队的顺序为:")
while(p->next!=p)
{
for(i=1i<=m1i++)
{
q=p
p=p->next
//printf("--\n",p->id)
}
m1=p->code
printf("%4d",p->id)
q->next=p->next
delete
p
p=q
}
printf("%4d",p->id)
delete
p
printf("\n")
}
}
void InitList(LinkList *&head)改成void InitList(LinkList **head),同时该函数中head全部改成*headvoid CreateListA同样处理。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)