约瑟夫问题的单向循环链表的代码实现

#include 
#include 
//链表节点
typedef struct node {
int data;
struct node *next;
}Node;


//创建一个单向循环链表 ,n表示创建的节点个数
Node *
createList(int n)
{
int i;
Node *head, *cur, *tmp;
head = (Node *)malloc(sizeof(Node));
if (head == NULL) {
printf("malloc error\n");
return NULL;
}
head->data = 1;
head->next = head;
tmp = head;


for (i = 2; i <= n; ++i) {
cur = (Node *)malloc(sizeof(Node));
if (cur == NULL) {
printf("malloc error\n");
return NULL;
}


cur->data = i;
cur->next = tmp->next;
tmp->next = cur;
tmp = cur;
} 


return head;
}
//打印链表节点数据
void
printNode(Node *head)
{
if (head == NULL) {
printf("head is NULL\n");
return;
}
printf("data:\n");


Node *tmp = head;

do {
printf("%d ", head->data);
head = head->next;
} while (head != tmp);


printf("\n");
}
//得到链表节点长度
int 
getListLen(Node *head)
{ 
Node *tmp = head;
int len = 0;
do {
++len;
head = head->next;
} while (head != tmp);


return len;
}


//约瑟夫问题
void
test(Node *head, int m)
{
int i,j;
Node *tmp;
int len = getListLen(head);

printf("result:\n");
for (i = 0; i < len; ++i) {
for (j = 0; j < m-2; ++j) {
head = head->next;
}
printf("%d ", head->next->data);
tmp = head->next;
head->next = head->next->next;
free(tmp);
head = head->next;
}
printf("\n");
}
//测试代码 约瑟夫问题的参数通过命令行传递


int
main(int argc, char **argv)
{
if (argc != 3) {
printf("usage: ./a.out m n\n");
exit(1);
}
int M = atoi(argv[1]);
int N = atoi(argv[2]);
Node *head = NULL;


head =  createList(M);
if (head == NULL) {
printf("createList error\n");
exit(1);
}
printNode(head);
yuesefu_test(head, N);
head = NULL;
return 0;
}


你可能感兴趣的:(约瑟夫问题的单向循环链表的代码实现)