| 查看: 334 | 回复: 2 | |||
[求助]
C++数据结构循环链表约瑟夫问题
|
|
#include <iostream> using namespace std; template <class T> struct Node { T data; Node<T> *next; }; template <class T> class CLinkList { public: CLinkList(){rear=new Node<T>;rear->next=rear;} CLinkList(T a[],int n); int Josephus(int m,int n); private: Node <T> *rear; }; template <class T> CLinkList<T>::CLinkList(T a[],int n) { rear=new Node<T>; rear->next=rear; for (int i=0;i<n;i++) { Node <T>*s=new Node <T>; s->data = a; s->next = rear->next; rear->next = s; rear = s; } Node <T>*p = rear->next; rear->next = p->next; delete p; } template <class T> int CLinkList<T>::Josephus(int m,int n) { int x,i; Node <T>*p=rear->next; if (n==1||m==1) { x=n; } else { while(n!=1) { i=1; while (p&&i!=(m-1)) { p=p->next; i++; } Node <T> *q = p->next; p->next = q->next; delete q; p = p->next; n--; } rear=p; x=p->data; } return x; } int main() { int M,N,a[1024]; cout<<"the number of people:"; cin>>N; if (N>=1024) { cout<<"Error!Please put in a smaller number."; return 0; } cout<<"the number they count:"; cin>>M; if (M<=0) { cout<<"Error!Please put in a positive number:"; return 0; } for (int i=0;i<N;i++) { a = i+1; } CLinkList<int> A(a,N); cout<<"the last number is:"<<A.Josephus(M,N)<<endl; return 0; } 我不知道在template <class T> CLinkList<T>::CLinkList(T a[],int n)的最后为啥要加上: Node <T>*p = rear->next; rear->next = p->next; delete p; 这一段代码,请高人指点,谢谢~~~ |
» 猜你喜欢
谈谈两天一夜的“延安行”
已经有15人回复
EST投稿状态问题
已经有6人回复
职称评审没过,求安慰
已经有15人回复
垃圾破二本职称评审标准
已经有11人回复
投稿Elsevier的Neoplasia杂志,到最后选publishing options时页面空白,不能完成投稿
已经有16人回复
毕业后当辅导员了,天天各种学生超烦
已经有4人回复
聘U V热熔胶研究人员
已经有10人回复
求助文献
已经有3人回复
投稿返修后收到这样的回复,还有希望吗
已经有8人回复
三无产品还有机会吗
已经有6人回复
libralibra
至尊木虫 (著名写手)
骠骑将军
- 程序强帖: 40
- 应助: 817 (博后)
- 金币: 12914.1
- 红花: 64
- 帖子: 2238
- 在线: 287.3小时
- 虫号: 696514
- 注册: 2009-02-05
- 专业: 计算机软件
【答案】应助回帖
感谢参与,应助指数 +1
libralibra
至尊木虫 (著名写手)
骠骑将军
- 程序强帖: 40
- 应助: 817 (博后)
- 金币: 12914.1
- 红花: 64
- 帖子: 2238
- 在线: 287.3小时
- 虫号: 696514
- 注册: 2009-02-05
- 专业: 计算机软件













回复此楼