<C>Josephus问题——用循环链表解决

来源:互联网 发布:华东理工大学网络教育 编辑:程序博客网 时间:2024/06/07 09:01

1.

刚刚学链表,因此这里特地用循环链表解决此问题。


2.

具体程序如下:

//joseph环问题:n个人排队,以m报数,直到只剩1人,输出此人编号//用循环链表解决问题#include<stdio.h>#include<malloc.h>int n,m;int i,k;//创建结构体struct student{        int number;        struct student *next;};void main(){        printf("n=");        scanf("%d",&n);        printf("\n");        printf("m=");        scanf("%d",&m);        printf("\n");        struct student *head,*p1,*p2;        for(i=0;i<n;i++)        {                if(i==0)                {                        p1=(struct student *)malloc(sizeof(struct student));                        p2=p1;                        head=p1;                        p1->number=1;                }                else                {                        p1=(struct student *)malloc(sizeof(struct student));                        p2->next=p1;                        p2=p1;                        p2->number=i+1;                        if(i==n-1)                        {                                p2->next=head;                        }                }        }        p1=head;        p2=head;        for(k=0;k<n;)        {                for(i=0;i<m-1;i++)                {                        p2=p1;                        p1=p1->next;                }                printf("number=%d\n",p1->number);                p2->next=p1->next;                head=p1->next;                p1=head;                p2=head;                k++;        }        printf("end number=%d",head->number);}

3.

单链表和循环链表的区别就在于最后一个结点->head

本质也是对结构体的运用

0 0
原创粉丝点击