#include<stdio.h>
#include<stdlib.h>
#define N 10
#define M 5
typedef struct node
{
int data;
struct node* next;
}DcNode;
//创建排队单链表
DcNode* CreatLink(DcNode* head,int n)
{
int i = 2;
DcNode* p = NULL, * r = NULL;
p = (DcNode*)malloc(sizeof(DcNode));
head = p;
head->data = 1;
head->next = head;
r = head;
for (i; i <= n; i++)
{
p = (DcNode*)malloc(sizeof(DcNode));
r->next = p;
r = p;
r->data = i;
r->next = head;
}
return head;
}
//输出循环链表
void DisLink(DcNode* head)
{
if (head == NULL)
{
printf("链表为空!\n");
return ;
}
DcNode *r = head;
do
{
printf("%d\t",r->data);
r = r->next;
} while (r != head);
printf("\n");
}
//销毁链表
void DesLink(DcNode* head)
{
DcNode* p = head, * q = NULL;
while(p != p)
{
q = p;
p = p->next;
free(q);
}
free(p);
}
//求解约瑟夫问题
void Yuesefu(DcNode *head,int m)
{
int j = 1;
DcNode * p = head, * pre = head, * q = NULL;
while (pre->next != p)
{
pre = pre->next;
}
while (p->next != p)
{
if (j == m)
{
j = 1;
q = p;
p = p->next;
pre->next = p;
printf("%d\t", q->data);
free(q);
}
else
{
p = p->next;
pre = pre->next;
j++;
}
}
printf("%d", p->data);
free(p);
printf("\n");
}
int main()
{
DcNode* head = NULL;
head = CreatLink(head,N);
DisLink(head);
Yuesefu(head,M);
return 0;
system("pause");
}