约瑟夫问题

来源:互联网 发布:佛山软件开发公司 编辑:程序博客网 时间:2024/05/04 19:00


这道题的算法思想就是先创建一个循环链表,然后在建一个指针,使其始终跟在头指针的后面,方便删除指定的结点。

代码如下:

#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
};
struct node *p;
struct node* Createlist(int n) /*创建一个循环链表*/
{
    struct node* head,*tail;
    int i;
    head=(struct node*)malloc(sizeof(struct node));
    head->data=1;/*头结点的值域不为空*/
    head->next=NULL;
    tail=head;
    for(i=2; i<=n; i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        p->data=i;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    tail->next=head;/*将尾指针指向头结点,构成循环链表*/
    return head;
};
int main()
{
    int m,n,k;
    struct node *head,*q;
    scanf("%d %d",&n,&m);
    head=Createlist(n);
    q=head;
    while(p->next!=head)/*让p指针跟在q的后面*/
        p=p->next;
    k=1;
    while(q->next!=q){
        if(k%m==0){
            p->next=q->next;
        }
        else{
            p=p->next;
        }
         q=q->next;
         k++;
    }
        printf("%d\n",q->data);
    return 0;
}

0 0
原创粉丝点击