65,209
社区成员
发帖
与我相关
我的任务
分享/* 链表的删除
* 题目:有15个人围成一圈,顺序从1到15编号。从第一个人开始报数,
* 凡报到n的人退出圈子。从键盘输入n的值,输出最后留在圈子
* 里的人的编号
*/
#define MAXN 15
#include <iostream>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}*Link;
Link createlist()
{
Link head = (Link)malloc(sizeof(struct node));
if (!head)
{
cout << "memory allocation error!" << endl;
exit(0);
}
head->data = 1;
head->next = head; //头结点指向自身,形成环形
for (int i=MAXN; i>1; i--)
{
Link p = (Link)malloc(sizeof(struct node));
if (!p)
{
cout << "memory allocation error!" << endl;
exit(0);
}
p->data = i; //头插,形成环形链表
p->next = head->next;
head->next = p;
}
return head;
}
int main()
{
Link p = createlist();
cout << "" ;
int n, k=MAXN;
cin >> n;
int c = 1;
Link q;
while(k>1)
{
if (n-1==c)
{
q = p->next;
p->next = q->next;
free(q);
c = 0;
k--;
}
else
{
c++;
p = p->next;
}
}
cout << "The last number is: " << p->data << endl;
}
cout << system("pause");
return 0;
}