#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int num;
struct node * next;
}Node, *Link;
int is_malloc_ok(Link new_node)
{
if (new_node)
return 0;
else
return 1;
}
void Create_new_node(Link *new_node)
{
int count = 10;
do
{
*new_node = (Link)malloc(sizeof(Node));
}while (count && is_malloc_ok(*new_node));
if (count == 0 && ! is_malloc_ok(*new_node))
{
printf("error: malloc failed!\n");
exit(-1);
}
}
void Create_Link(Link *head)
{
*head = NULL;
}
void Insert_node_head(Link *head, Link new_node)
{
Link p;
if (*head == NULL)
{
*head = new_node;
new_node->next = (*head);
}
else
{
p = *head;
while (p->next != *head)
{
p = p->next;
}
new_node->next = *head;
*head = new_node;
p->next = (*head);
}
}
void Insert_node_tail(Link *head, Link new_node)
{
Link p;
if (*head == NULL)
{
*head = new_node;
new_node->next = *head;
}
else
{
p = *head;
while (p->next != *head)
{
p = p->next;
}
p->next = new_node;
new_node->next = (*head);
}
}
void Display(Link head)
{
Link p;
p = head;
if (p == NULL)
{
printf("the link is empty!\n");
return;
}
if (p->next == head)
{
printf("%d\n", p->num);
return;
}
while (p->next != head)
{
printf("%d\n", p->num);
p = p->next;
}
printf("%d\n",p->num);
}
void Release(Link *head)
{
Link p, q;
if (*head == NULL)
{
printf("the link is empty!\n");
return;
}
else
{
while ((*head)->next != *head)
{
p = *head;
while (p->next != *head)
{
p = p->next;
}
q = *head;
(*head) = (*head)->next;
p->next = *head;
free(q);
}
free(*head);
*head = NULL;
}
}
void yoseph(Link *head)
{
Link p, q;
p = *head;
q = *head;
if (*head == NULL)
{
printf("the link is empty!\n");
return;
}
while ((*head)->next != *head)
{
p = p->next->next;
q = q->next;
if (p == *head)
{
*head = p->next;
q->next = *head;
q = *head;
}
else
{
q->next = p->next;
q = p->next;
}
free(p);
p = q;
}
printf("the left num is %d\n",(*head)->num);
}
int main()
{
Link head;
Link new_node;
int i = 0;
int n = 0;
printf("please input the number: ");
scanf("%d",&n);
Create_Link(&head);
for (i = 1; i <= n; i++)
{
Create_new_node(&new_node);
new_node->num = i;
Insert_node_tail(&head,new_node);
//Insert_node_head(&head,new_node);
}
Display(head);
yoseph(&head);
Release(&head);
return 0;
}