C语言 循环链表 约瑟夫问题

ecnu数据结构月考题:

循环链表解决约瑟夫问题

题目不是很难啦,单纯记录一下自己学习的足迹。
如果对于需要的人能有帮助,那真是再好不过了嘻嘻♪(・ω・)ノ

题目

在这里插入图片描述
在这里插入图片描述

代码

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

struct node{
    int name;
    struct node*next;
    };

int main()
{
    int n,m;
    struct node*head =(struct node*) malloc(sizeof(struct node));
    struct node*p,*q;
    int counts=1;
    int i;

    printf("This is a YSF(n,m) problem.\n");
    printf("Please input the integer n (n>=1).\n");
    scanf("%d",&n);
    printf("Please input the integer m (m>=1).\n");
    scanf("%d",&m);

    p=head;
    head->name=1;
    for(i=2;i<=n;i++){	//创建链表,并为每个结点编号。
        p->next=(struct node*)malloc(sizeof(struct node));
        p=p->next;
        p->name=i;
    }
    p->next=head;		//尾结点指针域指向头结点,构成环形链表。

    q=p;
    p=head;				//此时p指向头结点,q指向头结点的前一个结点。
    
    while(p!=p->next){		//跳出循环时,环形链表中只剩一个结点,指针域指向自身。
        for(counts=1;counts<m;counts++){//跳出循环时,p指向的是该被删除的结点。
            p=p->next;
            q=q->next;
        }
        printf("Get rid of : %d\n",p->name);
        q->next=p->next;
        p=p->next;			//把p指向的结点在链表中删除。
    }
    printf("The left element is : %d\n",p->name);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43467698/article/details/88798219