2012上机二 约瑟夫环


#include<stdio.h>
#include<stdlib.h>
void main() {
	int n, c,num=0,i=0,pos=-1;
	scanf("%d %d", &n, &c);
	int *a;
	a = (int *)malloc(sizeof(int) * n);
	for (int i = 0;i < n;i++)
		a[i]=0;
	while (num < n) {
		while (i<c) {
			pos = (pos + 1) % n;
			if(a[pos]==0)
				i++;
		}
		if (i== c) {
			i = 0;
			a[pos] = 1;
			printf("%d ", pos+1);
			num++;
		}
	}
}

用链表实现

//约瑟夫环(用链表实现)
typedef struct node {
	int data;
	node *next;
}*Linklist, node;
#include<stdio.h>
#include<stdlib.h>
void main() {
	node* rear, *p, *head, *pre;
	int n, m;
	printf("请输入人数:");
	scanf("%d", &n);
	head = (node*)malloc(sizeof(node));
	head->next = NULL;
	rear = head;
	for (int i = 1;i <= n;i++) {//初始化链表赋值1 2 3 4 。。。
		p = (node*)malloc(sizeof(node));
		p->data = i;
		p->next = NULL;
		rear->next = p;
		rear = p;
	}
	p = head;
	printf("请输入报数m:");
	scanf("%d", &m);
	while (p) {
		for (int i = 0;i < m;i++) {//数m个数
			if (p == NULL)
				break;
			if (p == rear) {
				pre = head;
				p = head->next;
			}
			else {
				pre = p;
				p = p->next;
			}
		}//for
		if (p != NULL) {
			printf("%d ", p->data);
			if (p == rear) {//p为尾结点
				if (rear == head->next)//p为链表中最后一个结点,程序结束
					return;
				pre->next = NULL;//p为尾结点,且p前面还有结点
				free(p);
				p = pre;rear = pre;
			}
			else {//p不为尾结点,位于链表中间,删除p
				pre->next = p->next;
				free(p);
				p = pre;
			}//if
		}//if
	}//while
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值