您的位置:首页 > 编程语言 > C语言/C++

C语言-----链表实现约瑟夫环

2013-05-07 21:44 295 查看
#include <stdio.h>
#include <stdlib.h>

#define CNT 10

typedef struct node{
int value;
struct node *next;
}list_node_t;

list_node_t *creat_node(int value);

void list_print_node(list_node_t *node_p);
void list_print_all(list_node_t *node_p);

list_node_t *list_insert_end_node(list_node_t *node_p, int value);

void josephus(list_node_t *node_p, int n);

int main(int argc, char **argv)
{
int i, num;
list_node_t *head = NULL;

for(i = 0; i < CNT; i++)
{

head = list_insert_end_node(head, i+1);
}
list_print_all(head);

fprintf(stdout, "Please input num:");
scanf("%d", &num);
josephus(head, num);

return 0;
}

list_node_t *creat_node(int value)
{
list_node_t *node_p;

node_p = malloc(sizeof(list_node_t));
if(node_p == NULL)
{
fprintf(stderr, "Malloc for creating node failed.\n");
exit(1);
}

node_p->value = value;
node_p->next = NULL;

return node_p;
}

void list_print_node(list_node_t *node_p)
{
fprintf(stdout, "p = %p value = %2d p->next = %p\n", node_p, node_p->value, node_p->next);
}

void list_print_all(list_node_t *node_p)
{
list_node_t *head = node_p;

while(head)
{
list_print_node(head);
head = head->next;

if(head == node_p)
break;
}
}

list_node_t *list_insert_end_node(list_node_t *node_p, int value)
{
list_node_t *new_node = creat_node(value);

if(new_node == NULL)
{
fprintf(stderr, "Creat new node failed.\n");
exit(1);
}

if(node_p == NULL)
{
node_p = new_node;
new_node->next = node_p;
return node_p;
}

list_node_t *p = node_p;
while(p->next)
{
p = p->next;
if(p->next == node_p)
break;
}

p->next = new_node;
new_node->next = node_p;

return node_p;
}

#if 1
void josephus(list_node_t *node_p, int n)
{
list_node_t *prev, *cur, *del;
int remain = CNT, step = 1;

prev = cur = node_p;
while(remain > 1)
{
if(step != n)
{
step++;
prev = cur;
cur = cur->next;
}
else
{
step = 1;
fprintf(stdout, "kill: value = %d\n", cur->value);
del = cur;
prev->next = cur = cur->next;
free(del);
remain--;
}
}
fprintf(stdout, "The lost num is: %d\n", cur->value);
}
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言 C 链表 小程序