来,耍起C语言的万能“三板斧”!
/* 读入问题条件 */printf("input total num:");scanf("%d", &n);printf("from which num begin:");scanf("%d", &k);if(k>n||k==0){printf("please input the right begin num");return 1; }printf("input the out num:");scanf("%d", &m);if(m>n||m==0){ printf("please input the right del num");return 2; }
typedef struct node{int data;struct node *next;}linklist;
/* 创建循环链表,头节点也存信息 */head = (linklist*) malloc(sizeof(linklist));p = head;p->data = 1;p->next = p;/* 初始化循环链表 */for (i = 2; i <= n; i++){s = (linklist*) malloc(sizeof(linklist));s->data = i;s->next = p->next;p->next = s;p = p->next;}
p = head;for (i = 1; i <= k; i++){p = p->next;}
total = n;printf("\nthe out num:");q = head;
/* 只剩一个节点时停止循环 */while (total != 1){/* 报数过程,p指向要删除的节点 */for (i = 1; i < m; i++){p = p->next;}/* 打印要删除的节点序号 */printf("[%d] ", p->data);/* q 指向 p 节点的前驱 */while (q->next != p){q = q->next;}/* 删除 p 节点 */q->next = p->next;/* 保存被删除节点指针 */s = p;/* p 指向被删除节点的后继 */p = p->next;/* 释放被删除的节点 */free(s);/* 节点个数减一 */total--;}/* 打印最后剩下的节点序号 */printf("\n\nthe last num:[%d] \n\n", p->data);free(p);}
好文章点赞、在看和分享一条龙吧❤️
评论
