耶稣有13个门徒, 其中有一个就是出卖耶稣的叛徒,请用排除法找出这位叛徒:13人围坐一圈,从第一个开始报号:1,2,3,1,2,3……,凡是报到“3”就退出圈子,最后留在圈内的人就是出卖耶稣的叛徒,请找出它原来的序号
#include <iostream>
using namespace std;
typedef struct Node{
int data;
struct Node *next;
} node;
int main(void){
node *head = new node;
head->next = head;
node *p = head;
p->data = 1;
int i;
for(i=12; i>0; i--){
node *p = new node;
p->data=i+1;
p->next = head->next;
head->next = p;
}
int count = 0;
node *q, *pq=NULL;
p = head;
cout << p->data << endl;
while(1){
count++;
q = p;
p = p->next;
cout << p->data << endl;
if(count==2){
if(pq == p){ // 最后只有两个节点的时候,p循环至pq的位置,故删除p,留下p->next
cout << "delete:" << p->data << endl;
cout << p->next->data << endl;
return 0;
}
cout << "delete:" << p->data << endl;
q->next = p->next;
delete[] p;
count = 0;
pq = p = q->next;
cout << p->data << endl;
}
}
return 0;
}