约瑟夫问题单向循环链表解决简版

作者在 2017-05-27 23:12:58 发布以下内容
#include<stdio.h>
#include<stdlib.h>
#define N 13      //总人数 

typedef struct Node
{
int Data;
struct Node *Next;
}List,*Position;

Position Create(void);
Position Delete(Position Head,Position P);
Position Deal(Position Head);
void Traverse(Position Head);

int main()  //测试 
{
Position Head=Create();
Traverse(Head);
Deal(Head);
Traverse(Head);
return 0;
}

Position Create(void)
{
int i;
Position Head=NULL,Tail=NULL,New=NULL;

Head=malloc(sizeof(struct Node));
if(Head==NULL)
{
printf("内存不足\n");
exit(0);
}
Tail=Head;
for(i=0;i<N;i++)
{
New=malloc(sizeof(struct Node));
if(New==NULL)
{
printf("内存不足\n");
exit(0);
}
New->Data=i+1;
New->Next=NULL;
Tail->Next=New;
Tail=New;
}
Tail->Next=Head;
return Head;
}

Position Deal(Position Head)  //主要处理函数 
{
Position Cursor=Head;    //表头 
Position Deletion=NULL;

int Label=0; 
int Cir=3;  //数数的最高值 

while(Cursor->Next->Next!=Cursor)  //当前指向的不是表头时 
{
Label++;
if(Label==Cir)  //case1 数到3 
{
   Label=0;
Deletion=Cursor->Next;
printf("%5dth person is out \n",Deletion->Data);
Cursor->Next=Deletion->Next;     //删除操作 
free(Deletion);
}
else     //case 2 数到1、2 
{
Cursor=Cursor->Next; 
}
if(Cursor->Next==Head)  //case 3  链尾 
{
Cursor=Head;    
}
}
printf("%5dth person reserved!\n",Cursor->Next->Data);  //输出最后一个人 
}

void Traverse(Position Head)  //遍历 
{
Position Cursor=Head->Next;
printf("目前的留下情况:");
while(Cursor!=Head)
{
printf("%d ",Cursor->Data);
Cursor=Cursor->Next;
}
printf("\n");
}
c++基础 | 阅读 1856 次
文章评论,共0条
游客请输入验证码