Luo Gu || C language linear table to solve Joseph's problem

One sentence of the day, to the most precious you: Learn to adapt to different environments, and whether you change together with the environment will determine what kind of life you start!

The title describes
n people in a circle, starting from the first person to count, the person who counts to m is listed, and then the next person starts to count from 1 again, and the person who counts to m goes out of the circle, and so on. Until all the people are out of the circle, please output the numbers of the people who are out of circle in turn.

Input format
Input two integers n, m.

Output format
Output a line of n integers, and output the number of each person in the circle in order.

Input and output sample
input

10 3
output

3 6 9 2 7 1 8 5 10 4

Source code:


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

typedef struct Node {
    
    
    int data;
    struct Node *next;
}ListNode;

typedef ListNode *LinkList;

LinkList InitList (int n,LinkList L);
LinkList ListDelete(int n,int m,LinkList L);

int main() {
    
    
    LinkList L;
    int n,m;
    scanf("%d %d",&n, &m);
    L=InitList(n,L);
    L=ListDelete(n,m,L);
    //return 0;
}

LinkList InitList (int n,LinkList L) {
    
    
    ListNode *p, *q;
    int i;
    L = (ListNode *) malloc(sizeof(ListNode));
    q=L;//q为临时变量,将头节点赋值给q
    for (i = 1; i <= n; i++) {
    
    
        p = (ListNode *) malloc(sizeof(ListNode));
        p->data =i;//初始化p的data
        q->next=p;//将q指向p的首地址
        q=p;//p为尾结点,将p赋值给临时变量q
    }
    p->next=L->next;//使最后一个结点指向第一个结点,使之构成一个循环
    return L;
}

LinkList ListDelete(int n,int m,LinkList L){
    
    
    int i,l;
    ListNode *p, *q;
    p=L;
    for(i=1;i<=n;i++){
    
    
        for(l=1;l<m;l++){
    
    
            p=p->next;//p是第l-1个(待删除项)
        }
        q=p->next;
        p->next=q->next;
        printf("%d ",q->data);
        free(q);
        L=p;
    }
    return L;
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46259251/article/details/109262737