循环链表之约瑟夫问题
来源:互联网 发布:南风知我意林如斯txt 编辑:程序博客网 时间:2024/05/18 20:07
约瑟夫环问题:一圈共有N个人,开始报数,报到M的人自杀,然后重新开始报数(自杀的人的下一位),问最后自杀的人是谁?
这里取N=41,M=3.
#include<iostream>#include<stdlib.h>using namespace std;typedef int ElemType;struct Node{Node* next;ElemType data;};typedef Node LinkList;Node* Create(int n)//尾插法创建循环链表{Node *head,*p,*q;head=new Node;head->next=NULL;q=head;for(int i=0;i<n;i++){p=new Node;p->data=i+1;q->next=p;q=p;}p->next=head->next;free(head);return p->next;}void main(){int n=41;int m=3;m%=n;Node *p=Create(n);Node *temp;while(p!=p->next){for(int i=1;i<m-1;i++){p=p->next;//是p指向自杀节点的上一个}printf("%d->",p->next->data);temp=p->next;//自杀节点p->next=temp->next;free(temp);p=p->next;//移动p使其为自杀节点的下一个}printf("%d",p->data);}打印出自杀顺序:
阅读全文