18.约瑟夫环
?用單循環(huán)鏈表做的。
代碼.
/*這是約瑟夫環(huán) */ #include<iostream> using namespace std;typedef struct node {int data;struct node* next; }Link;void josephus(int n,int m) {//用循環(huán)鏈表做Link *head,*tail;int i,j;head=NULL;tail=NULL;for(i=0;i<n;i++){Link* temp=new Link;temp->data=i;temp->next=NULL;if(head==NULL){head=temp;tail=temp;}else{tail->next=temp;tail=temp;}}tail->next=head;//循環(huán)鏈表建成//first指針指向每次開(kāi)始的節(jié)點(diǎn),最后一次時(shí)它應(yīng)該指向自己Link* pre=tail;Link* first=head;while(first->next!=first){for(j=1;j<m;j++){pre=first;first=first->next;}//first指向的出列//cout<<first->data<<"出"<<endl;//刪除first這個(gè)指針Link* temp=first;pre->next=first->next;first=first->next;delete temp;temp=NULL;}cout<<first->data<<"出"<<endl;delete first;first=NULL; } int main(void) {int m,n;cin>>n>>m;josephus(n,m);return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/buxianghe/p/3216634.html
總結(jié)
- 上一篇: WPF制作的一个小功能,智能提示(Int
- 下一篇: Central Authenticati