约瑟夫问题(80)

来源:互联网 发布:unity3d粒子特效教程 编辑:程序博客网 时间:2024/06/10 12:13

源代码:

//    约瑟夫问题//    功能:用链表实现约瑟夫问题 #include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#include <malloc.h>typedef struct jose {int number;int cipher;struct jose *next;} Joseph;Joseph *create(int num) {Joseph *head, *ptr, *ptr1;int i;head = (Joseph*)malloc(sizeof(Joseph));if (head == NULL) {printf("Error");return ptr1;}ptr = head;ptr->next = head;for (i = 1; i < num; i++) {if ((ptr1 = (Joseph*)malloc(sizeof(Joseph))) == NULL) {printf("Error");return ptr1;}ptr->next = ptr1;ptr = ptr1;}ptr->next = head;return head;}int main() {int i, m = 1, n = 20;Joseph *ptr, *head;time_t t;srand(time(&t));head = create(n);for (i = 1; i <= n; i++) {head->number = i;head->cipher = rand() % 10 + 1;head = head->next;}ptr = head;i = 1;while (head->next != ptr) {head = head->next;}while (head->next != head) {if (i == m) {ptr = head->next;printf("number: %d\t", ptr->number);printf("cipher: %d\n", ptr->cipher);m = ptr->cipher;head->next = ptr->next;free(ptr);i = 1;}else {head = head->next;i++;}}printf("number: %d\t", head->number);printf("cipher: %d\n", head->cipher);free(head);return 0;}

运行结果:


0 0
原创粉丝点击