joseph.c

来自「实现约瑟夫环」· C语言 代码 · 共 100 行

C
100
字号
#include<stdio.h>
#include<malloc.h>
typedef struct LNode{
    int number;
    int password;
    struct LNode *next;
    }LNode, *Joseph;
Joseph Init_Link(){
    Joseph circle;
    circle=(Joseph)malloc(sizeof(LNode));
    circle->number=1;
    circle->next=circle;
    return circle;
    }
void Insert_Node(Joseph link,int password,int number){
    Joseph insert_addr,temp;
    insert_addr=(Joseph)malloc(sizeof(LNode));
    insert_addr->password=password;
    insert_addr->number=number;
    temp=link;
    while(temp->next!=link)
    temp=temp->next;
    insert_addr->next=link;
    temp->next=insert_addr;
    }
void Delete_Node(Joseph last){
    Joseph delete_addr,temp;
    temp=last;
    delete_addr=temp->next;
    temp->next=delete_addr->next;
    free(delete_addr);
    }
int main(){
    Joseph circle,temp,last;
    int i,m,n,counter,password;
    printf("Please input the initial m:\n");
    scanf("%d",&m);
    if(m<=0){
        printf("Your number is not avilable,Please input again(the number shuld be above zero).\n");
        scanf("%d",&m);
        }
    printf("Please input the number of players:\n");
    scanf("%d",&n);
    if(n<=0){
        printf("Your number is not avilable,Please input again(the number shuld be above zero).\n");
        scanf("%d",&n);
        }
    circle=Init_Link();
    printf("Please input the 1's password:\n");
    scanf("%d",&circle->password);
    for(i=2;i<=n;i++){
        printf("Please input the %d's password:\n",i);
        scanf("%d",&password);
    if(password<=0){
        printf("Your number is not avilable,Please input again(the number shuld be above zero).\n");
        scanf("%d",&password);
        }
    Insert_Node(circle,password,i);
    }
    temp=circle;
    printf("The right list is:\n");
    if(m==1){
        printf("%d->",temp->number);
        m=temp->password;
        while(temp->next!=circle)
        temp=temp->next;
        Delete_Node(temp);
        for(counter=1;temp->next!=temp;counter++){
            last=temp;
            temp=temp->next;
            if(counter==m){
                printf("%d->",temp->number);
                m=temp->password;
                Delete_Node(last);
                temp=last;
                counter=0;
                }
            }
            printf("%d",temp->number);
        }
    else{
        for(counter=2;temp->next!=temp;counter++){
            last=temp;
            temp=temp->next;
        if(counter==m){
            printf("%d->",temp->number);
            m=temp->password;
            Delete_Node(last);
            temp=last;
            counter=0;
            }
        }
    printf("%d",temp->number);
    }
    getch();
}

 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?