循环单链表实现约瑟夫环

来源:互联网 发布:关口知宏上海 编辑:程序博客网 时间:2024/05/21 22:34

n个人围成一圈报数,数到3的人出局:

//约瑟夫环//循环链表实现#include<stdio.h>#include<stdlib.h>typedef int elemtype;typedef struct node{int num;          //序号                //elemtype data;    struct node *next;}*linklist;void Joseph(int n);void Joseph(int n){linklist p, q, s;elemtype e;int countSum = n;//总计数int count = 1;s = (linklist)malloc(sizeof(node));//第一个节点if (!s) exit(0);s->num = 1;//s->data = 1;s->next = NULL;p = s; //q = s;for (int i = 2; i <= n; i++){q = (linklist)malloc(sizeof(node));q->num = i;//q->data = 1;p->next = q;q->next = NULL;p = q;}p->next = s;p = s->next;q = s;while (countSum> 2){p = p->next;q = q->next;count++;if (count == 2){q->next = p->next;e = p->num;printf("kill %d\n",e);free(p);p = q->next;count = 0;countSum--;}//if}//whileprintf("remain:\n");printf("%d->",p->num);//输出剩下的第1个元素p = p->next;printf("%d->", p->num);//输出剩下的第2个元素}void main(){int n;printf("输入参加人数:");scanf("%d",&n);Joseph(n);system("pause");}

0 0
原创粉丝点击