标题:单链表实现约瑟夫环
只看楼主
Love嵌入式
Rank: 1
等 级:新手上路
帖 子:84
专家分:0
注 册:2008-3-4
 问题点数:0 回复次数:0 
单链表实现约瑟夫环
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef struct stu
{
    int num;
    int move;
    int pwd;
    struct stu *next;
}Node,*Linklist;

void kong(Linklist &L)
{
    L=(Linklist)malloc(sizeof(Node));
    L->next=NULL;
}

void creat(Linklist &L,int n)
{
    int i;
    Linklist r,s;
    r=L;
      for(i=1;i<=n;i++)
    {
        s=(Linklist)malloc(sizeof(Node));
        s->num=i;
        s->move=i;
        printf("请输入第%d个人的密码:",i);
        scanf("%d",&s->pwd);
        r->next=s;
        r=s;
    }
    r->next=NULL;
}


void huan(Linklist &L,int n,int m)
{
  int out,x,f,j;
  f=x=1;
  Linklist p,h,g,p1,g1;
  p1=L;
  p=L->next;
  g=L->next;
  while(p)
  {
   
    out=m%n;
    if(out==0) out=n;

    if(p->move==out)
    {
        printf("\n%d",p->num);
           m=p->pwd;
        n--;
        
        h=p;
        p=p->next;
        free(h);
        if(out==1)
        {
            L->next=p;
        }
        else
        {
        for(;x<f;x++)
            p1=p1->next;

        if(p==NULL)
        {
            p=L->next;
            p1->next=NULL;
        }
        else
        {
          p1->next=NULL;
          L->next=p;
          g1=p;
          while(p->next)
              p=p->next;
          p->next=g;
          g=g1;
        }
        }
        p=L->next;
        for(j=1;j<=n;j++)
        {
          p->move=j;
          p=p->next;
        }
        p=L->next;
        g=L->next;
        x=f=1;
        p1=L;
    }
    else
    {
        p=p->next;
        f++;
    }
  }
}



void main()
{
    Linklist L;
    int m,n;
    printf("上限m=");
    scanf("%d",&m);
    printf("人数n=");
    scanf("%d",&n);
    kong(L);
    creat(L,n);
    huan(L,n,m);
    getch();
    free(L);
}
搜索更多相关主题的帖子: 约瑟夫 单链 int Linklist Node 
2008-03-16 14:32



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-203666-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 1.121653 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved