/* 题目: 约瑟夫环问题。 思路: 用链表list实现,注意判断链表在末尾时,使其指向开头, 每次循环删除一个数字,直到只剩下一个数字。 */ #include<iostream> #include<list> using namespace std; int LastRemaining(unsigned int n,unsigned int m){ if(n < 1|| m < 1) return -1; list<int> numbers; for(int 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; } int main(){ cout<<LastRemaining(5,3); }