/* 15个人排成一圈,给他们1——15的编号 数到4的人退出,余下的人从下一个位置重新开始报数,直到最后只剩下一个人
问 这个人是几号?
*/
==================数组实现==========================
- #include <iostream>
- #include <stdio.h>
- using namespace std;
- int list[15];
- void print()
- {
- cout<<"----------剩下的元素为-------------"<<endl;
- for (int i=0;i<15;i++)
- {
- cout<<list[i]<<endl;
- }
- }
- void init()
- {
- for (int i=0;i<15;i++)
- {
- list[i]=i+1;
- }
- }
- void setposition(int *&p) //这个函数是最难的地方
- {
- int sum=0;
- int a=3;
- while(sum!=a)
- {
- if (!*p)
- { //p为0的时候 也 就是说传递进来的是0,所以a=4;
- a=4;
- while (!*p) //找到下一个不为0的点。
- {
- p++;
- if (p==list+15)
- {
- p=list;
- }
- }
- }
- else
- { //p不为0的时候
- p++;
- if (p==list+15) //注意检验p是否为最后一个元素。
- {
- p=list;
- }
- if (!*p)
- {
- while (!*p)
- {
- p++;
- if (p==list+15)
- {
- p=list;
- }
- }
- }
- }
- sum++;
- }
- }
- int main()
- {
- init();
- int *p=list;
- for (int count=0;count<14;count++)
- {
- setposition(p);
- *p=0;
- print();
- }
- return 0;
- }
=================链表实现===========================
- #include <iostream>
- #include <stdio.h>
- using namespace std;
- struct list
- {
- int data;
- list * next;
- };
- list *head=new list;
- list *tail=head;
- void add()
- {
- head->data=1;
- for (int i=2;i<16;i++)
- {
- list *p=new list;//记得清零
- memset(p,0,sizeof(p));
- tail->next=p;
- p->data=i;
- p->next=head;
- tail=p;
- }
- }
- void out()
- {
- cout<<endl<<endl<<endl;
- cout<<"剩下的人:"<<endl;
- list *p=head;
- // printf("head:%d\ttail:%d\t\n",head,tail);
- while(p!=tail)
- {
- cout<<p->data<<endl;
- p=p->next;
- }
- // cout<<p->data<<endl;
- // cout<<"out over"<<endl;
- // int _a_;cin>>_a_;
- }
- void remove()
- {
- list *p=head;
- list *lastp=p;
- for(int count=0;count<14;count++)
- {
- out();
- p=p->next;
- for (int i=0;i<2;i++)
- {
- lastp=lastp->next;
- p=p->next;
- }
- // cout<<"free "<<p->data<<endl;
- lastp->next=p->next;
- if (p==head) //here;
- {
- head=lastp->next;
- }
- if (p==tail)
- {
- tail=lastp;
- }
- free(p);
- p=lastp->next;
- lastp=p;
- }
- }
- int main()
- {
- add();
- remove();
- return 0;
- }
=========================================
感想:本来用链表完了以后觉得挺麻烦的,这问题用数组解决应该很容易,一实践才发现根本不是那回事,数组需要考虑的非常周密,编写的过程中犯了很多错误,只好一点一点修改解决。
现在快累死了,从7点到十点。解决了这个问题,总的来说 还是有一点收获的。
2011年12月26日 21:57:43
转载于:https://blog.51cto.com/awsam/751675