数据结构(循环链表)实现约瑟夫问题

来源:互联网 发布:手机怎么申请淘宝介入 编辑:程序博客网 时间:2024/05/21 23:47
#include<stdio.h>#include<stdlib.h>typedef struct node{int data;struct node *next;}node;node *create(int n){int i;node *p = NULL,*head;node *temp;head = (node*)malloc(sizeof(node));p=head;for(i=1;i<=n;i++){temp = (node*)malloc(sizeof(node));temp->data = i;p->next = temp;p=temp;}temp->next = head->next;free(head);return temp->next;}int main(){int m,n,i;node *temp;//用于释放节点node *p;printf("输入人数:");scanf("%d",&m);printf("输入出局密码:");scanf("%d",&n);p=create(m);if(n>1){while(p!=p->next){for(i=1;i<m-1;i++){//找到要剔除的前一个人p = p->next;}printf("%d",p->next->data);temp = p->next;p->next = temp->next;free(temp);p = p->next;}printf("%d\n",p->data);}else{for(i=1;i<=m;i++){printf("%d",i);}}return 0;}


原创粉丝点击