您的位置:首页 > 其它

链表的应用:利用无头结点循环链表解决约瑟夫环问题

2014-01-17 00:21 671 查看
链表的应用:利用无头结点循环链表解决约瑟夫环问题
     数据结构实训的时候做的,没有张老师的实训真遗憾。何老师说代码最好多多注释,这样以后应聘的时候才会让人觉得代码习惯不错~当当当~

     寒假了,整理整理贴上来~

     注意:当这个链表中只剩下一个结点的时候应该结束循环,单独输出最后一个结点,否则会在删除结点这一步出现错误。

     细节+代码如下:

     #include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(people)

int N,count,K,f;

typedef struct people{ //链表结构。
int num;
struct people *next;
}people;

people *create(int t){ //创建一定长度的链表。
int n;
people *head,*p1,*p2;
p1 = p2 = (people*)malloc(LEN);
head = NULL;
n = 1;
while(n<=N){
p1->num = n;
if(n==1)
head = p1;
else
p2->next = p1;
p2 = p1;
if(n!=N)
p1 = (people*)malloc(LEN);
n++;
}
p2->next = head;
return head;
}

people *start(people *L,int f){ //找到最开始报数的那个人。
int n;
people *point;
point = L;
n = 1;
while(n!=K){
point = point->next;
n++;
}
return point;
}

people *delete(people *head){ //出列函数。
int i,j,k;
people *p;
p = head;
k = 0;
while(N>1){
j = 0;
for(i = 1+k;i<=N;i++){
if((i+1)%count==0){
printf("%d ",p->next->num);
p->next = p->next->next;
j++;
i++;
}
p = p->next;
k = i%count;
}
N = N-j;
}
printf("%d\n",p->num);
return p;
}

int main(){
int f;
people *L,*st;
scanf("%d%d",&N,&count); //分别为约瑟夫环的长度和要出列的数字。
L = create(N);
scanf("%d",&K); //开始报数的人。
st = start(L,K);
f = 1;
delete(st);
return 0;
}

/*
* 测试案例:
*
* 输入:
* 10 3 1 //分别为总数,出列的人数到的数字,开始数的人的编号。
*
* 输出:
* 3 6 9 2 7 1 8 5 10 4 //按照出列的先后顺序给出的出列的人的编号。
*
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: