链表的应用1_josephus问题

声明:

#include "stdio.h"
#include "stdlib.h"
#define FALSE 0
#define TRUE 1
typedef int DataType;
struct Node;//单链表的结点类型
typedef struct Node *PNode;//结点指针类型
//单链表结点结构
struct Node {
    DataType info;
    PNode link;
};
typedef struct Node *LinkList;
typedef LinkList *PLinkList;

 

2.初始化链表

//用1,2,……,n为*pclist所示的循环表初始化
int init_clist(PLinkList pclist,int n)
{
    PNode p,q;
    int i;
    q=(PNode)malloc(sizeof(struct Node));
    if(q==NULL)
    {
        return FALSE;
    }
    *pclist=q;
    q->info=1;
    q->link=q;
    if (n==1) 
    {
        return TRUE;
    }
    for(i=2;i<n+1;i++)
    {
        p=(PNode)malloc(sizeof(struct Node));
        if(p==NULL)
        {
            return FALSE;
        }
        p->info=i;
        p->link=q->link;
        q->link=p;
        q=p;
    }
    return TRUE;
}

 

3.对josephus问题的算法

void josephus_clist(PLinkList pclist,int s,int m)
{
    PNode p,pre;
    int i;
    p=*pclist;
    //找到第s个元素
    if (s==1) 
    {
        pre=p;
        p=p->link;
        while (p!=*pclist)
        {
            pre=p;
            p=p->link;
        }
    }
    else
    {
        for(i=1;i<s;i++)
        {
            pre=p;
            p=p->link;
        }
    }
    while (p!=p->link) 
    {
        //当链表中结点个数大于1时,找到第m个结点。
        for(i=1;i<m;i++)
        {
            pre=p;
            p=p->link;
        }
        //输出该结点
        printf("out element: %d \n",p->info);
        
        //该结点是第一个结点时,删除是需要特殊处理下
        if (*pclist==p) 
        {
            *pclist=p->link;
        }

        pre->link=p->link;
        free(p);
        p=pre->link;
    }

    printf("out element :%d \n",p->info);
    free(p);
}

 

测试main函数:

int main()
{
    LinkList jos_clist;
    int n,m,s;

    do {
        printf("\n please input the value of n=");
        scanf("%d",&n);
    } while(n<1);

    do {
        printf("\n please input the value of s=");
        scanf("%d",&s);
    } while(s<1);

    do {
        printf("\n please input the value of m=");
        scanf("%d",&m);
    } while(m<1);

    if(init_clist(&jos_clist,n))
    {
        josephus_clist(&jos_clist,s,m);
    }
    else
    {
        printf("out of space! \n");
    }
    return 1;
}

 

 

 

结果:

 

posted on 2012-05-08 15:01  yucong  阅读(222)  评论(0)    收藏  举报

导航