有一个数组a[N]顺序存放0~N-1,要求每隔两个数删掉一个数,到末尾时循环至开头继续进行,求最后一个被删掉的数的原始下标位置。以8个数(N=7)为例:{0,1,2,3,4,5,6,7},0->1->2(删除)->3->4->5(删除)->6->7->0(删除),如此循环直到最后一个数被删除。
输入描述:
每组数据为一行一个整数n(小于等于1000),为数组成员数,如果大于1000,则对a[999]进行计算。
输出描述:
一行输出最后一个被删掉的数的原始下标位置。
输入例子1:
8
输出例子1:
6
代码:
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node* ptrtonext;
typedef ptrtonext List;
typedef ptrtonext Position;
struct node {
int data;
ptrtonext next;
};
List createlist(int n)
{
Position p1, p2;
Position head = NULL;
p1 = (Position)malloc(sizeof(struct node));
p1->data = 0;
p1->next = NULL;
head = p1;
p2 = p1;
for (int i = 1; i<n; i++)
{
p1 = (Position)malloc(sizeof(struct node));
p1->data = i;
p1->next = NULL;
p2->next = p1;
p2 = p1;
}
p2->next = head;
return head;
}
int main()
{
Position head, p1, p2;
int N;
cin >> N;
head = createlist(N);
p1 = head;
for (; p1->next != p1;)
{
p1 = p1->next;
p2 = p1->next;
p1->next = p2->next;
p1 = p1->next;
free(p2);
}
cout << p1->data;
while (1);
}