問題描述:n我的圍成一個環,從第i個開始,由1到interval不斷報數,凡報到interval的出列,直到環空爲。出列的人按前後順序構成一個新的序列。例如,n=8,i=2,interval=3.則輸出序列爲:4 7 2 6 3 1 5 8ios
代碼以下:函數
#include <iostream>spa
#include <iomanip>指針
using namespace std;code
struct Jonse //定義單鏈表結構體ip
{int code;ci
Jonse *next;input
};io
Jonse *Create(int);//聲明建立鏈表函數stream
void ShowList(Jonse *);//聲明表示輸出鏈函數
void Out(Jonse*,int,int);//聲明輸出被刪結點的號碼的函數
int main()
{Jonse *head;
int num,val,beg;//num是結點數目,val是間隔,beg是開始的位置
cout<<"\nplease input the number of total:\n";
cin>>num;//輸入結點數目
head=Create(num);//建立數目爲num的鏈表
ShowList(head);//表示輸出鏈表
cout<<"\nplease input the code of begin:\n";
cin>>beg;//輸入節點報數開始位置
cout<<"\nplease input intervel of counting:\n";
cin>>val;//輸入報數間隔大小
cout<<"the new list is:\n";
Out(head,beg,val);//依次輸出被刪的結點號碼
system("pause");
}
Jonse *Create(int n)//建立鏈表
{Jonse *h,*p;
int i;
h=new Jonse;//h爲頭指針
p=h;
for(i=1;i<=n;i++)//p的做用是把n個鏈表賦值
{p->code=i;
if(i<n)
{p->next=new Jonse;
p=p->next;
}
}
p->next=h;
return h;
}
void ShowList(Jonse *h)//輸出建好的鏈表
{Jonse *p;
p=h;
do
{cout<<p->code<<'\t';
p=p->next;
}while(p!=h);
}
void Out(Jonse *h,int i,int d) //*h是頭指針,i是開始位置,d是間隔
{Jonse *p,*q;
int k;
p=h;
for(q=h;q->next!=h;q=q->next);//把q指向頭指針的前驅
for(k=1;k<i;k++)//尋找最初開始的位置
{q=p;
p=p->next;
}
while(p!=p->next)//處理鏈環,直到最後一個結點
{for(k=1;k<d;k++)//報數,輸出
{q=p;
p=p->next;
}
cout<<p->code<<'\t';//輸出被刪的結點
q->next=p->next;//刪除結點
delete p;
p=NULL;
p=q->next;
}
cout<<p->code<<endl;//輸出最後一個結點
delete p;
p=NULL;
}
運行結果以下: