现在的位置: 首页 > 综合 > 正文

约瑟夫问题简单实现-循环链表

2018年03月21日 ⁄ 综合 ⁄ 共 531字 ⁄ 字号 评论关闭

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
int  data;
struct node * next;

}node;

node * create(int n)
{
node *p=NULL,*head;
head=(node*)malloc(sizeof(node));
p=head;
node * s;
int i=1;
if(0!=n)
{
while(i<=n)
{
s=(node*)malloc(sizeof(node));
s->data=i++;
p->next=s;
p=s;
}
s->next=head->next;
}
free(head);
return s->next;
}

int main()
{
int n=41;
int m=3;
node *p=create(n);
node *temp;
    m%=n;
while(p!=p->next)
{
for(int i=1;i<m-1;i++)
{
p=p->next;
}
printf("%d->",p->next->data);
temp=p->next;
p->next=temp->next;
free(temp);
p=p->next;
}
printf("%d\n",p->data);
free(p);
return 0;
}

抱歉!评论已关闭.