数据结构实验——约瑟夫环

. Experimental purpose:

  • Understand the basic logical structure of linear list, and complete the implementation of linked list and circular linked list
  • Through experiments, we can further understand the logical structure and storage structure of linear list, improve the ability to use theoretical knowledge to guide and solve practical problems, and master the practical application of linked list.

二. Experimental content:

Title: Josephus ring problem

Problem description:

One description of Joseph's problem is that n individuals numbered 1,2,..., n sit clockwise. Select a positive integer as the upper limit of the number m. from the k person, the number shall be reported in clockwise direction from 1, and the number shall be stopped when the person reporting m is reported. The person reporting m shall list, and the next person in clockwise direction shall start to report from 1 number again until all the people are listed. Try to design a program to find out the sequence.

Basic requirements:

This process is simulated by using the one-way circular linked list storage structure, and the numbers of each person are printed in the order of listing.

#include "stdio.h"
#include "stdlib.h"

typedef struct LNode {
    int data;
    struct LNode* next;
}LNode, * LinkList;

LinkList Create(int n) {
    int flag = 1;
    LinkList L;
    LNode* s, * rear;
    L = (LinkList)malloc(sizeof(LNode));
    L->data = flag;
    flag++;
    rear = L;
    while (flag <= n) {
        s = (LNode*)malloc(sizeof(LNode));
        s->data = flag;
        rear->next = s;
        rear = rear->next;
        flag++;
    }
    rear->next = L;
    return L;
}

void Pri(LinkList L, int m, int n, int k) {
    // k开始节点,m出列数字,n节点总数
    LNode* rear,*free1;
    rear = L;
    int flag = 0;
    int k1 = 0 ,rear1=1;
    while (rear1 < n) {
        rear = rear->next;
        rear1++;
    }

    while (k1 < k - 1) {
        rear = rear->next;
        L = L->next;
        k1++;
    }
    k1 = 0;
    while (flag < n) {
        while (k1 < m - 1) {
            rear = rear->next;
            L = L->next;
            k1++;
        }
        printf("%d", L->data);
        printf("  ");
        L = L->next;
        free1 = rear->next;
        rear->next = rear->next->next;
        free(free1);
        k1 = 0;
        flag++;
    }
}

int main() {
    int m, n, k;
    printf("请输入结点总数:\n");
    scanf("%d", &n);
    printf("请输入开始结点数:\n");
    scanf("%d", &k);
    printf("请输入出列数字");
    scanf("%d", &m);
    LinkList L;
    L = Create(n);
    Pri(L, m, n, k);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值