求用c语言编写约瑟夫环的程序

求用c语言编写约瑟夫环的程序,第1张

#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")

}

}

正好之前写过基础的察雀约瑟夫环,稍作修改就可以满足你的题目

#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

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12474277.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存