这些都是很久以前自学编写的小程序,很经典,贴出来和大家分享下 ^-^
【题目】有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
提示:用环形链表实现
</pre><pre class="csharp" name="code">/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co., Ltd.
File name:
Author:Jerey_Jobs Version:0.1 Date:
Description:环形链表实现报数留人
Funcion List:
*****************************************************/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct node
{
int num;
struct node * next;
};
typedef struct node Node;
typedef struct node * link;
void is_malloc_ok(link *head)
{
if(*head == NULL)
{
printf("malloc is error!\n");
exit(-1);
}
}
void create_link(link *head)
{
(*head) = (link)malloc(sizeof(Node));
is_malloc_ok(head);
*head = NULL; //环形链表
}
void create_node(link *new_node, int i)
{
(*new_node) = (link)malloc(sizeof(Node));
is_malloc_ok(new_node);
(*new_node)->num = i;
}
void insert_node(link *head, link *new_node)
{
(*new_node)->next = *head;
*head = *new_node;
}
void remove_node(link *head, int n)
{
link p1 = NULL;
link p2 = NULL;
int i, count = 0;
i = n;
while(i > 1)
{
if(p1 == NULL)
{
p1 = *head;
}
count++;
if(3 == count)
{
if(p1 == *head)
{
p2 = *head;
*head = (*head)->next;
p1 = *head;
free(p2);
}
else
{
p2->next = p1->next;
p2 = p1;
p1 = p1->next;
free(p2);
}
count = 0;
i--;
}
else
{
p2 = p1;
p1 = p1->next;
}
}
}
void display(link *head)
{
link tmp;
tmp = (*head);
while(tmp != NULL)
{
printf("%3d", tmp->num);
tmp = tmp->next;
}
printf("\n");
}
int main()
{
int n, i;
link head = NULL;
link new_node = NULL;
printf("请输入要报数的总人数:");
scanf("%d", &n);
create_link(&head);
for(i = n; i >= 1; i--)
{
create_node(&new_node, i);
insert_node(&head, &new_node); //将这n个人加入到链表中
}
printf("原先的人员编号:\n");
display(&head);
printf("删除后的人员为:\n");
remove_node(&head, n);
display(&head);
return 0;
}