圆圈中最后剩下的数字
N个人围一圈报数,数到3 退出,最后一个是几号 (1)自定义链表 typedef struct Node { int value; struct Node* next; }Node ,*Link; Link creat(int n){ Link node=new Node; node->value=n-1; Link pre,rear; rear=pre=node; for(int i=n-2;i>=0;i--){ node =new Node; node->value=i; node->next=pre; pre=node; } rear->next=pre; return pre; } int LastRemaining(int m,Link list){ Link p=list,q; int i=0; while(p->next!=p){ i++; if(i==m-1){ q=p->next; p->next=q->next; delete q; i=0; } p=p->next; } int last=p->value; return last; } int _tmain(int argc, _TCHAR* argv[]) { Link list=creat(5); int result=LastRemaining(3,list); printf("%d\n",result); } (2)使用std::list int LastRemaining_Solution1(unsigned int n, unsigned int m) { if(n < 1 || m < 1) return -1; unsigned int i = 0; list<int> numbers; for(i = 0; i < n; ++ i) numbers.push_back(i); list<int>::iterator current = numbers.begin(); while(numbers.size() > 1) { for(int i = 1; i < m; ++ i) { current ++; if(current == numbers.end()) current = numbers.begin(); } list<int>::iterator next = ++ current; if(next == numbers.end()) next = numbers.begin(); -- current; numbers.erase(current); current = next; } return *(current); } 时间O(mn),空间O(n) // ====================方法2==================== int LastRemaining_Solution2(unsigned int n, unsigned int m) { if(n < 1 || m < 1) return -1; int last = 0; for (int i = 2; i <= n; i ++) last = (last + m) % i; return last; } 时间O(n),空间O(1);