报数离开队列游戏
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node;
Node *createList(int total);
void Josephus(struct Node *p1, int total, int from, int count);
int main(int argc, char const *argv[])
{
int total, from, count;//total总人数,from第一个报数的人 , count出列者喊的数
struct Node *L=NULL;
scanf("%d%d%d", &total, &from, &count);
L = createList(total);
Josephus(L, total, from, count);
return 0;
}
Node *createList(int total)
{
struct Node *p=NULL, *head=NULL;
int i;
for(i=1; i<=total; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = i;
if(head == NULL)
{
head = newNode;
}
else
{
p->next = newNode;
}
p = newNode;
}
p->next = head;//循环链表
return head;
}
void Josephus(struct Node *p1, int total, int from, int count)
{
int i;
for(i=1; i<from; i++)
{
p1 = p1->next;//将指针定位到表示第一个报数的人的结点处
}
struct Node *p2=NULL;
//循环的删除队列中报数到count的结点
while(p1->next != p1)//只剩首位相连的最后一个节点时结束
{
for(i=1; i<count; i++)
{
p2 = p1;
p1 = p1->next;//p1定位出出列者结点p2为其前一个结点
}
p2->next = p1->next;
printf("Delete number: %d\n", p1->data);
free(p1);
p1 = p2->next;//恢复p1不断指向新节点的功能
}
printf("The last one is NO.%d\n", p1->data);
}
此解法是学习链表时看的别人的解法,非原创,但看的谁的文章来着忘记了,望见谅_||