约瑟夫环算法

来源:互联网 发布:项目数据分析 编辑:程序博客网 时间:2024/05/22 03:30

建立了8个人从第一个数每数到3则出局

#include <stdio.h>#include <stdlib.h>#include<malloc.h>#include<string.h>//定义一个节点结构体typedef struct node{int data;struct node *next;}Node;//建立一个约瑟夫循环链表Node *Create_Link(int n){ Node *head,*p,*q; int i; p=(Node *)malloc(sizeof(Node)); //注意赋值 否则是个垃圾数据 p->data=1; p->next=NULL; head=p; for(i=2;i<=n;i++){  q=(Node *)malloc(sizeof(Node));  q->data=i;  p->next=q;  p=q; } p->next=head; return head;}// 约瑟夫环// 从第m个人开始报数(1<=m<=创建链表的那个参数n),数到n的那个人被杀死void  jesefu(Node *head,int m,int n){  Node *p,*q;  int i=0;//相隔从i到n之前的距离  p=head;  //找到第m个人  while(p->data!=m){      p=p->next;  }  //杀死报道n的人  while(p->next!=p){   for(i=0;i<n-1;i++){    q=p;    p=p->next;   }   printf("出局的顺序%d\n",p->data);   q->next=p->next;   free(p);   p=q->next;  }  printf("最后剩下的为%d\n",p->data);  free(p);}int main(){  Node * head=Create_Link(8);  jesefu(head,1,3);  system("pause");    return 0;}

这里写图片描述

原创粉丝点击