Joseph Problem C code, Joseph c code
1/* Joseph Problem 2 * solve the Joseph Problem by using a single-loop linked list. 3 * Problem description: Links n numbers into a ring. Starting from the m number, Every time from 1 count to s, 4 * deletes s. Delete s when counting from 1 to s again from the next one. Until all five parts are deleted. 6 **/7 # include <stdio. h> 8 # include <stdlib. h> 9 10 typedef struct Node {11 int data; 12 struct Node * next; 13} Node; 14 typedef struct Node * LinkList; 15 16 void createjoseph phloop (LinkList * L, int number) {17 // create the Joseph ring and put the element 1.18 * L = (LinkList) malloc (sizeof (struct Node) in the header knot; 19 if (! (* L) {20 printf ("Error: malloc: 0! \ N "); 21 exit (1); 22} 23 (* L)-> next = (* L); 24 (* L)-> data = 1; 25 int I; 26 LinkList new; 27 LinkList tail = * L; 28 for (I = 1; I <number; I ++) {29 new = (LinkList) malloc (sizeof (struct Node); 30 if (! New) {31 printf ("Error: malloc: 1 + I"); 32 exit (1); 33} 34 new-> data = I + 1; 35 new-> next = tail-> next; 36 tail-> next = new; 37 tail = new; 38} 39} 40 void Joseph problem (int loopSize, int from, int stepBy) {41 // loopSize: Joseph ring size 42 // form: Starting from 43 // stepBy: delete the element 44 LinkList L pointed to by stepBy each time it is counted to stepBy; 45 createjoseph phloop (& L, loopSize); 46 int seekStart = 1; 47 while (seekStart <from) {48 L = L-> next; 49 seekStart + = 1; 5 0} 51 while (L-> data! = L-> next-> data) {52 int I = 1; 53 LinkList temp; 54 for (I = 1; I <stepBy-1 ;) {55 L = L-> next; 56 I ++; 57} 58 temp = L-> next; 59 printf ("% d -->", temp-> data ); 60 L-> next = L-> next; 61 L = L-> next; 62 free (temp); 63} 64 printf ("% d \ n ", l-> data); 65} 66 int main () {67 Joseph problem (10, 3, 4); 68 Joseph problem (41,1, 3); 69 return 0; 70}