C语言-----链表实现约瑟夫环
2013-05-07 21:44
295 查看
#include <stdio.h> #include <stdlib.h> #define CNT 10 typedef struct node{ int value; struct node *next; }list_node_t; list_node_t *creat_node(int value); void list_print_node(list_node_t *node_p); void list_print_all(list_node_t *node_p); list_node_t *list_insert_end_node(list_node_t *node_p, int value); void josephus(list_node_t *node_p, int n); int main(int argc, char **argv) { int i, num; list_node_t *head = NULL; for(i = 0; i < CNT; i++) { head = list_insert_end_node(head, i+1); } list_print_all(head); fprintf(stdout, "Please input num:"); scanf("%d", &num); josephus(head, num); return 0; } list_node_t *creat_node(int value) { list_node_t *node_p; node_p = malloc(sizeof(list_node_t)); if(node_p == NULL) { fprintf(stderr, "Malloc for creating node failed.\n"); exit(1); } node_p->value = value; node_p->next = NULL; return node_p; } void list_print_node(list_node_t *node_p) { fprintf(stdout, "p = %p value = %2d p->next = %p\n", node_p, node_p->value, node_p->next); } void list_print_all(list_node_t *node_p) { list_node_t *head = node_p; while(head) { list_print_node(head); head = head->next; if(head == node_p) break; } } list_node_t *list_insert_end_node(list_node_t *node_p, int value) { list_node_t *new_node = creat_node(value); if(new_node == NULL) { fprintf(stderr, "Creat new node failed.\n"); exit(1); } if(node_p == NULL) { node_p = new_node; new_node->next = node_p; return node_p; } list_node_t *p = node_p; while(p->next) { p = p->next; if(p->next == node_p) break; } p->next = new_node; new_node->next = node_p; return node_p; } #if 1 void josephus(list_node_t *node_p, int n) { list_node_t *prev, *cur, *del; int remain = CNT, step = 1; prev = cur = node_p; while(remain > 1) { if(step != n) { step++; prev = cur; cur = cur->next; } else { step = 1; fprintf(stdout, "kill: value = %d\n", cur->value); del = cur; prev->next = cur = cur->next; free(del); remain--; } } fprintf(stdout, "The lost num is: %d\n", cur->value); } #endif
相关文章推荐
- 约瑟夫环的C语言链表实现
- C语言单链表实现约瑟夫环
- C语言实现单链表之约瑟夫环
- 自杀环---约瑟夫环(单链表经典面试题)------>C语言实现
- 单向链表的C语言实现
- C语言实现约瑟夫环问题
- C语言单链表实现19个功能完全详解
- C语言学习历程(十四) 结构体链表实现通讯录
- C语言实现链表之双向链表(二)结点内存申请及数据初始化
- 单链表的实现和相关面试题及其详解(C语言)
- 自己按照书上实现的c语言的单链表
- 单链表插入和删除结点c语言的实现
- C语言用数组1. 简单约瑟夫环问题: N个人,编号从1~N围成一圈,输入一个数T,从1号开始报数,报到T的人出圈;下一人又从1开始报数,下一个报到T的人出圈,输出出圈顺序。 考虑问实现约瑟夫环问题
- 带表头的单向链表实现(C语言)
- C语言链表基本函数的递归实现
- C语言实现单链表(LinkedList)
- C语言实现链表
- C语言算法实现约瑟夫环1
- 数据结构之链表结构——C语言实现
- 将两个非递减的有序链表合并为一个非递增的有序链表(C语言编程实现)