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

#include <stdlib.h>
#include <string.h>
//链表节点
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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值