循環鏈表---約瑟夫環

#include <iostream>
using namespace std;

typedef struct student
{
	int data;
	struct student* next;
}node,*LinkList;
//約瑟夫環
void printfList(LinkList head){

	LinkList p=head;
	if (head!=NULL)//忘了這個
	{

		do{
			cout<<p->data<<" ";
			p=p->next;
		}while(p!=head);//這裏出現過問題,用do-while
		cout<<endl;
	}
}
void Josephus(int n,int k,int m){
	int i=2;
	LinkList head=(LinkList)malloc(sizeof(node));
	head->next=head;
	head->data=1;
	LinkList pre=head;
	while(i<=n){
	    LinkList p=(LinkList)malloc(sizeof(node));
		p->data=i;
		p->next=pre->next;
		pre->next=p;
		pre=p;
		i++;
	}
	printfList(head);

	LinkList mend=pre;
	int kk=0;
	while(kk!=k){
		mend=mend->next;
		++kk;
	}//找到k個開始
	
	while(n--){//要全部輸出
		int mm=1;
		pre=mend;//每次都要給pre從新復值否則程序錯誤
		while(mm!=m){//不是要求的數,指針每次往前推一步,mend指向報數的人,pre指向前一個
			pre=mend;
			mend=mend->next;
			mm++;
		}
		pre->next=mend->next;//前一個鏈到下一個準備報數的
		cout<<mend->data<<endl;
		LinkList deletem=mend;
		mend=pre->next;//mend指向報數的人;
		free(deletem);	//最後刪除	
	}
}
int main(){
	Josephus(13,4,1);
	return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章