数据结构-约瑟夫环
2015-12-16 22:49
330 查看
#include <stdio.h> #include <malloc.h> typedef struct node{ int key; int num; struct node * next; }node, * plist; //顺序创建 int init(plist * L, int all_num){ plist p; int i; *L = p = (plist)malloc(sizeof(node)); p->num = 1; p->next = NULL; for(i = 2; i <= all_num; i++){ p->next = (plist)malloc(sizeof(node)); p = p->next; p->num = i; p->next = NULL; } p->next = *L; return 1; } //显示 void Print(plist L, int all_num) { plist p; int i = 0; p = L; while (p && i!=all_num) { printf("%d ", p->num); p = p->next; i++; } printf("\n"); } //输入key void Input(plist L, int all_num) { plist p; int i = 0; p = L; while (p && i!=all_num) { printf("%d的key是多少?", p->num); scanf("%d", &p->key); p = p->next; i++; } } //删除节点 void delete(plist * L, plist p){ plist swap = *L; while(swap){ if(swap->next == p){ swap->next = p->next; if(*L == p) *L = swap->next; free(p); break; } swap = swap->next; } } int main(void) { plist L, p, swap; int all_num, kill_num, j, count; puts("多少人围一圈?"); scanf("%d", &all_num); puts("初始key?"); scanf("%d", &kill_num); if(!init(&L, all_num)) puts("初始化失败"); puts("初始化成功,编号已给!"); Print(L, all_num); puts("请输入密码"); Input(L, all_num); puts("开始!"); count = 0; j = 1;//依次报数 swap = p = L; while(count != all_num){ if(kill_num == j){ Print(L, all_num-count); printf("从%d开始数 key为%d\n", swap->num, kill_num); printf("%d出列\n\n", p->num); kill_num = p->key; swap = p->next; delete(&L, p); p = swap; j = 1; count++; continue; } j++; p = p->next; } if(count == all_num) printf("ok\n"); // L = p = swap = NULL; return 0; }
相关文章推荐
- 数据结构上机4队列-杨辉三角2
- 数据结构上机4队列-杨辉三角1
- 数据结构上机3栈-括号匹配
- 数据结构上机2单链表合并 非递减
- 数据结构上机1顺序表
- 考研系列之三-数据结构杂集
- 数据结构和算法经典100题-第22题
- 【C#数据结构】快速排序
- 【C#数据结构】简单选择排序
- memcached-数据结构
- 【C#数据结构】直接插入排序
- 数据结构实验4(排序算法的实现及性能分析)
- Redis文件事件处理用到的基本数据结构视图
- 数据结构--Chapter6(图)
- Linux Kernel中的数据结构---- 其它
- 数据结构之归并排序
- 数据结构之插入排序
- 2015年大二上-数据结构-数组与广义表(2)-4.下三角矩阵的压缩存储及基本运算
- 2015年大二上-数据结构-数组与广义表(2)-3.上三角矩阵的压缩存储及基本运算
- 一、redis 数据结构使用场景