题目:
有一堆人围一圈,开始从1开始编号,每个人数到3的人,推出,然后继续从下一个1开始数数,直到剩下最后一个人。用编程实现。
#include<iostream>
#include<stdio.h>
using namespace std;
//定义数据结构
typedef struct personNode
{
int num;
struct personNode *next;
}personNode;
personNode *head = NULL;
personNode *cur = NULL;
int sumPerson = 0;//总的人数
int currentPersons = 0; //记录当前剩余的人数
//需要的函数
personNode* createLink(int n);//根据人数创建节点
void deleteNode(personNode*);//删除指定节点
void main()
{
printf("请输入总的人数:");
scanf("%d",&sumPerson);
currentPersons = sumPerson;
head = createLink(sumPerson);//根据人数创造相应的链表
cur = head;
personNode *temp = NULL;
//循环给予链表节点的编号
int i = 1;
while(currentPersons--)
{
cur->num = i++;
cur = cur->next;
}
currentPersons = sumPerson;
cur = head;
//循环判断,符合条件的节点,输出编号并删除
while(currentPersons-- != 1)
{
temp = cur->next->next->next;
cur = cur->next->next;
printf("=",cur->num);
deleteNode(cur);
cur = temp;
}
free(cur);
cur = NULL;
}
//创建新节点
personNode* createLink(int n)
{
//第一个节点
personNode *head1 = (personNode *)malloc(sizeof(personNode));
head1->num = 0;
head1->next = NULL;
cur = head1;
personNode *NewNode = NULL;
while(1 != n--)
{
NewNode = (personNode *)malloc(sizeof(personNode));
NewNode ->num = 0;
NewNode ->next = NULL;
cur->next = NewNode;
cur = NewNode;
}
cur->next = head1;
return head1;
}
//删除指定节点
void deleteNode(personNode* node)
{
//找到节点的上一节点
personNode *upNode = NULL;
upNode = node;
while(upNode->next != node)
{
upNode = upNode->next;
}
//更改指针,释放节点
upNode->next = node->next;
free(node);
node = NULL;
}