(2013-4-21)数据结构实验三:狐狸逮兔问题(方法二:链式)

#include
#include

#define OK 1
#define OVERFLOW -2

typedef int status;

typedef struct Snode
{
	int key;
	int flag;
	struct Snode *next;

}Snode,*LinkList;

//初始化
status InitList_Sql(LinkList *L)
{
	*L = (LinkList)malloc(sizeof(Snode));
	
	if(*L==NULL)
	{
		exit(OVERFLOW);
	}

	(*L)->next = NULL;

	return OK;
}

//创建
status CreakList(LinkList *L, int n)
{
	int i;
	LinkList p, q;
	q = *L;

	q->key = 1;	//一号洞
	q->flag = 1;	//标记未进过的洞为1

	for(i = 2; i <= n; i++)
	{
		p = (LinkList)malloc(sizeof(Snode));
		p->key = i;
		p->flag = 1;	

		q->next = p;
		q = p;
	}

	q->next = *L;	//循环链表

	return OK;

}

//查找
status findRabbit(LinkList *L,int n,int count)
{
	int i,j,find = 1;
	LinkList p = *L;
	p->flag = 0;	//一号洞开始被查找了

	for(i = 2; i <= count; i++)
	{
		for(j =0; j < i; j++)
		{
			p = p->next;
		}

		p->flag = 0;
	}

	for(i = 1; i<= n; i++)
	{
		if(p->flag == 1)
		{
			printf("兔子可能藏在第%d号洞\n",p->key);
			
			find = 0;
		}

		p = p->next;
	}

	if(find)
	{
		printf("兔子无藏身之处!");
	}

	return OK;

}

void main()
{
	int n, count;
	LinkList L;
	InitList_Sql(&L);
	
	printf("请输入洞数n = ");
	scanf("%d",&n);
	CreakList(&L,n);

	printf("请输入狐狸寻找的次数count = ");
	scanf("%d",&count);
	findRabbit(&L,n,count);
}

你可能感兴趣的:(算法与数据结构)