基于循环链表的约瑟夫问题(八)

来源:互联网 发布:飞思卡尔单片机选型 编辑:程序博客网 时间:2024/06/01 07:45
基于循环链表的约瑟夫问题
约瑟夫问题具体细节可以百度百科下。

下面给出基于循环链表的约瑟夫问题的代码

typedef struct CLinkList{int data;struct CLinkList* next;}node;node *create(int n){node *head =  (node*)malloc(sizeof(node)) ;node *p = NULL;//p指向当前结点int i =1;p = head ;node *temp;if(n!=0){while(i<=n){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 n = 41;node *p = create(n);node *temp;int m = 4; //表示间隔数m %= n;while(p != p->next){for(int 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);return 0;}



0 0