萌新哪位大神帮我注释一下这个约瑟夫环代码

青椒肉丝aa 发布于 2017/05/12 20:07
阅读 141
收藏 0

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

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


void insertItem(node_t* node, int x){
    node_t* newNode;
    newNode = (node_t*)malloc(sizeof(node_t));
    newNode->data = x;
    newNode->next = NULL;
    while(node->next != NULL){
        node = node->next;
    }
    node->next = newNode;
}
int deleteItem(node_t* node, int x){
    while(node->next->data != x && node->next != NULL){
        node = node->next;
    }
    if(node->next == NULL){
        return 0;
    }
    else{
        node_t* tempNode = node->next->next;
        node_t* oldNode = node->next;
        oldNode = NULL;
        free(oldNode);
        node->next = tempNode;
        return 1;
    }
}
void makeList2Cycle(node_t* node){
    node_t* firstNode = node;
    while(node->next != NULL){
        node = node->next;
    }
    node->next = firstNode;
}
void text(node_t* node){
    int count = 0;
    while(count != 10 && node != NULL){
        printf("%d ", node->data);
        node = node->next;
        count++;
    }
    printf("\n");
    /*if(node)*/
    /*printf("%d\n",node->data);*/
}
int main()
{
    int n, m;
    scanf("%d %d",&n,&m);/*n is the number of student; m is the stopping;*/
    node_t* node;
    node = (node_t*)malloc(sizeof(node_t));
    node->data = 0;
    node->next = NULL;
    int i;
    for(i = 1; i <= n ; i++){
        insertItem(node,i);
    }
    /*text(node);*/
    makeList2Cycle(node);
    /*text(node);*/
    int count = 0;
    int x = -1;
    while(node->next->data != node->data){
        count++;
        if(node->data == 0){
            node = node->next;
        }
        if(count == m){
            x = node->data;
            deleteItem(node,x);
            count = 0;
       /*     printf("*****%d\n",x);*/
            /*text(node);*/
        }
        /*text(node);*/
        node = node->next;
    }
    printf("%d\n",x);
    return 0;
}

加载中
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部