約瑟夫環(c語言指針編寫)

思路
**1.**使用兩個指針(移動和刪除)
**2.**創建單循環鏈表
**3.**查找並刪除

# include <stdio.h>
# include <stdlib.h>
typedef struct Node
{
 int data;
 int num;
 struct Node *next;
};
    struct Node *Create_List(int n)
{
 int c,i=1,j;
 struct Node *rear,*s,*CL;
 CL=(struct Node*)malloc(sizeof(struct Node));
 CL->next=CL;                          
 rear=CL;
 for(j=0;j<n;j++)
 {
  s=(struct Node*)malloc(sizeof(struct Node));
  scanf("%d",&c);
  s->data=c;
  s->num=i;
  i++;
  rear->next=s;
  rear=s;
 }
 rear->next=CL->next ;
 return CL;
}
 struct Node*fun(struct Node *CL,int m)
 {
  int i;
  struct Node *p,*q;
  p=CL;
 for(i=1;i<=m;i++)
 {
  q=p;
  p=p->next;
 }
 printf("%d ",p->num);
 q->next=p->next;
 CL=p;
 return CL;
 }
 void main()
 {
  int n,m,a;
  struct Node*CL;
  printf("請輸入m:");
  scanf("%d",&m);
  printf("請輸入人數n:");
  scanf("%d",&n);
  printf("請輸入每個人的密碼:");
  CL=Create_List(n);
  printf("出列的順序爲:");
  CL=fun(CL,m);
  a=n-1;
  while(a!=1)
  {
   CL=fun(CL,CL->data);
   a--;
  }
  printf("\n最後剩下的人:%d",CL->next->num);
  printf("\n"); 
  return 0;
 }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章