题目链接:http://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
结合题意:就是n个人从0连续编号到n-1,然后围成一圈,给一个m每次第m个人退出圈,接着往后,这个就是模拟链表删除结点,最后剩下的就是目标结点;
题目不难,注意细节,比如m<=0;n<=0之类的,这些都是要自己考虑的,即使题目没说;
我之前做过一个技巧性更强的题:http://www.cnblogs.com/yuyixingkong/p/3254566.html 有兴趣的可以看下;
#include<stdio.h> #include<stdlib.h> typedef struct List { int val; struct List *next; List(int x) : val(x),next(NULL) {} }List; class Solution { public: int LastRemaining_Solution(unsigned int n, unsigned int m) { if(n==0||m==0) return -1; if(m==1)return n-1; List *L,*p; L=CreatList(L,n); int k=0; while(L) { // printf("k=%d\n",k); k++; if(k%m==0) { p->next=L->next; // printf("-----%d\n",L->val); free(L); L=p->next; k=1; } p=L; L=L->next; if(p==L) return p->val; } } List* CreatList(List *pHead,int n) { if(n==0) return NULL; List *p,*q; pHead=new List(NULL); p=pHead; int xx=0; p->val=xx; while(--n) { q=new List(++xx); p->next=q; p=q; } p->next=pHead; return pHead; } }; int main() { Solution so; int n,m; scanf("%d%d",&n,&m); int ans=so.LastRemaining_Solution(n,m); printf("%d\n",ans); return 0; } /* 测试用例: 0,0 对应输出应该为: -1 */