循环链表范例(约瑟夫问题)指针实现

#include<stdlib.h>
#include<stdio.h>
#include<math.h>


typedef struct node* link;  //链接
struct node
{
	int item;
	link next;  
};//节点


int main(void)
{
	int N,M;
	
	printf("输入人数N\n");
	printf("输入N的底数:");
	scanf("%d", &N);
	getchar();
	
	printf("输入N的指数:");
	scanf("%d", &M);
	getchar();
	
	N=pow(N,M);
	
	
	printf("输入间隔M:");
	scanf("%d", &M);
	getchar();
	
	link t=malloc(sizeof *t),x=t;  
	t->item=1; t->next=t;
	//t指向首个节点 x指向下一个节点
	
	for(int i=2; i<=N; i++)
	{
		x=(x->next=malloc(sizeof*x));
		x->item=i; 
	}
	//创建链表 t>x1>x2>...>t
	x->next=t;
	while(x!=x->next)
	{
		for(int i=1; i<M; i++)
			x=x->next;
		//遍历数出M-1个元素
		free(x->next);
		x->next=x->next->next;
		//将第M个元素删除指向下个
		N--;
	}
	printf("%d\n",x->item);
	
	free(x);	
	return 0;
}

posted on 2018-02-03 10:26  MACHINE_001  阅读(154)  评论(0编辑  收藏  举报

导航