Ⅰ 數據結構(c語言版)編程
約瑟夫環問題
#include<stdio.h>#include<stdlib.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node *next;
}slink;
void onlyone(int n);
void list(slink *head);
void onlyone(int n)
{
slink *head,*p,*q;
int i,m,k;
p=head=(slink*)malloc(sizeof(slink));
for(i=1;i<=n;i++)
{
q=(slink*)malloc(sizeof(slink));
q->data=i;
p->next=q;
p=q;
}
p->next=head;
p=head;
m=0;
while(m<n-1)
{
k=0;
while(k<3)
{
k++;q=p;p=p->next;
if(p==head)
{q=p;p=p->next;}
}
q->next=p->next;
free(p);
p=q;
m++;
}
list(head);
}
void list(slink *head)
{
slink *p;
p=head->next;
while(p!=head)
{
printf("%4d",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
int a;
printf("請輸入人數:");
scanf("%d",&a);
onlyone(a);
}
帶頭結點雙向循環結點的與瑟夫環問題
#include<stdio.h>#include<stdlib.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node *next;
struct node *prior;
}dlink;
void onlyone(int m,int n,int k);
void list(dlink *head);
void onlyone(int m,int n,int k)
{
dlink *head,*p,*q;
int i;
if(m<1||n<1||k<1)
{printf("Error!\n");exit(0);}
p=head=(dlink*)malloc(sizeof(dlink));
for(i=1;i<=m;i++)
{
q=(dlink*)malloc(sizeof(dlink));
q->data=i;
q->prior=p;
p->next=q;
p=q;
}
p->next=head;
head->prior=p;
p=head;
while(m>1)
{
for(i=1;i<=n;i++)
{
q=p;p=p->next;
if(p==head) {q=head;p=head->next;}
}
q->next=p->next;
p->next->prior=q;
free(p);
p=q->next;
m--;
if(m>1)
{for(i=1;i<=k;i++)
{
q=p;p=p->prior;
if(p==head)
{q=p;p=p->prior;}
}
q->prior=p->prior;
p->prior->next=q;
free(p);
p=q->prior;
m--;
}
}
list(head);
}
void list(dlink *head)
{
dlink *p;
p=head->next;
while(p!=head)
{
printf("%4d",p->data);
p=p->next;
}
printf("\n");
p=head->prior;
while(p!=head)
{
printf("%4d",p->data);
p=p->prior;
}
printf("\n");
}
int main()
{
int a,b,c;
printf("請輸入需要創建的自然數個數:");
scanf("%d",&a);
printf("請輸入沿順時針方向去掉的第n個數:");
scanf("%d",&b);
printf("請輸入沿逆時針方向去掉的第m個數:");
scanf("%d",&c);
onlyone(a,b,c);
}