約瑟夫環問題是比較經典的問題,原來做的題目是依次輸出數字,而原來的循環鏈表結構不改變,今天遇到一道題是要求按照順序重新組成一個循環單鏈表。
題目:一些人圍坐一圈報數,形成一個循環單鏈表,當報數是m或m的倍數時出將節點從單鏈表中刪除,重新加入新的循環單鏈表,最後形成一個新的循環單鏈表。
- struct Node
- {
- int data;
- Node *next;
- };
- void circle(Node** head,int m)
- {
- Node* tmp1=*head;
- Node *tmp2=(*head)->next;
- int cnt=1;
- while(1)
- {
- cnt++;
- if(cnt%m==0)
- {
- *head=tmp2;
- tmp1->next=tmp2->next;
- tmp2=tmp2->next;
- break;
- }
- else
- {
- tmp1=tmp1->next;
- tmp2=tmp2->next;
- }
- }
- Node *tmp3=*head;
- while(tmp1!=tmp2)
- {
- cnt++;
- if(cnt%m==0)
- {
- tmp3->next=tmp2;
- tmp3=tmp3->next;
- tmp1->next=tmp2->next;
- tmp2=tmp2->next;
- }
- else
- {
- tmp1=tmp1->next;
- tmp2=tmp2->next;
- }
- }
- tmp3->next=tmp2;
- tmp2->next=*head;
- }
- int main( int argc, char** argv )
- {
- Node a[10];
- for(int i=0;i<9;i++)
- {
- a[i].data=i+1;
- a[i].next=&a[i+1];
- }
- a[9].data=10;
- a[9].next=&a[0];
- Node *aa=&a[0];
- Node **aaa=&aa;
- circle(aaa,5);
- return -1;
- }
原始:1 2 3 4 5 6 7 8 9 10 1 2 。。。
結果:5 10 6 2 9 8 1 4 7 3 5 10 6 2 。。。