Use a circular linked list to implement Joseph ring (number of perimeter loops) and number of perimeter Loops
At the beginning, I learned C and encountered the classic circle report number problem. Now I will first attach the implementation code below:
# Include <stdio. h>
# Include <stdlib. h>
Struct LNODE {// linked list definition
Int data;
Struct LNODE * next;
};
Typedef struct LNODE Lnode;
Typedef struct LNODE * LinkList;
Struct LNODE * create (int s []) // create a single cyclic linked list
{
Struct LNODE * head = NULL, * p = NULL, * last = NULL;
Int I = 0;
Head = (struct LNODE *) malloc (sizeof (struct LNODE ));
If (! Head)
Printf ("memory allocation error! ");
If (s [0]! = 0)
{
Head-> data = s [0];
Head-> next = head;
Last = head;
I ++;
While (s [I]! = 0) // determines whether it is 0. If it is 0, it ends.
{
P = (struct LNODE *) malloc (sizeof (struct LNODE ));
Last-> next = p;
P-> data = s [I];
P-> next = head;
Last = p;
I ++;
}
}
Return head;
}
Void printlist (struct LNODE * head) // print the circular linked list
{
Struct LNODE * q;
Int I;
Printf ("the linked list is: \ n ");
If (! Head)
Printf ("NULL ");
Else
{
Q = head;
Do
{
Printf ("% d \ t", q-> data );
Q = q-> next;
} While (q! = Head );
}
Printf ("\ n ");
}
Int main ()
{
Int circlelist [100], n, I, k = 1;
Printf ("please input the number :");
Scanf ("% d", & n); // number of input persons
Getchar ();
For (I = 0; I <n; I ++)
Circlelist [I] = I + 1; // number each person
Circlelist [I] = 0; // The last value is 0.
For (I = 0; I <= n; I ++)
Printf ("% d \ t", circlelist [I]); // print the number
LinkList p = NULL, q = NULL;
P = create (circlelist );
Printlist (p); // print the serial linked list
While (p-> data! = P-> next-> data) // exit the loop when it is equal to itself
{
If (k! = 3) // set the number of registrants to 3 to exit
{
K ++;
Q = p;
P = p-> next;
}
Else
{
K = 1;
Printf ("% d \ t", p-> data); // print the employee ID
Q-> next = p-> next; // Delete the worker node of report 3
P = q-> next;
}
}
Printf ("\ n % d \ n", p-> data );
}
At the beginning of the pointer definition, the value is not NULL, and debugging is not correct, but cannot be executed.
It is suggested that if the pointer is not used for definition, the value is NULL first. I think it is best to do this. In addition, when using the pointer, we should judge whether it is NULL.