程序代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define LEN 41
#define NUM 3
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
LNode* CreateLinklist(LNode *L)
{
int i;
LNode *p,*q;
L=(LNode*)malloc(sizeof(LNode));
assert(L!=NULL);
p=L;
for(i=0;i<LEN;i++)
{
q=(LNode*)malloc(sizeof(LNode));
assert(q!=NULL);
q->data=i+1;
p->next=q;
p=q;
}
p->next=L->next;
free(L);
return p->next; //返回循环链表第一个节点
}
void PrintLinklist(LNode *head)
{
LNode *p,*q;
p=head;
while(p->next != p)
{
for(int i=1;i<NUM-1;i++) //找到删除的前驱节点
{
p=p->next;
}
printf("%d-->",p->next->data);
q=p->next; //把要删除的结点赋给q
p->next=q->next;
free(q); //释放掉删除结点
p=p->next;
}
printf("%d",p->data);
}
/*约瑟夫问题*/
int main()
{
LNode *L,*temp;
temp=CreateLinklist(L);
PrintLinklist(temp);
return 0;
}
运行截图: