The essence of a linked list
Code
#include <bits/stdc++.h>//c++ Magnum header file, write this other header file without writing using namespace std;//use namespace, you do not have to tube typedef struct NODE// The node holds one data and pointer to the next node {int data;//data field struct node *pnext;//pointer field, and must point to the next pointer variable of the same type node struct node this type} node; node *create (int n)//create a circular linked list of n nodes, the function name preceded by * indicates a pointer to the node type {//first create a 1th node *p,*q,*head;//p,q,head is a pointer variable that points to the struct node type, which can be Think of it as an assignment int i; p = (node *) malloc (sizeof (node)); The//malloc function allocates memory space for p dynamically head = p;//Head is the first node p->data = 1; for (i = 2;i<=n;i++)//create remaining node {q = (node *) malloc (sizeof (node))///Add new node so reallocate memory space, dynamically allocate q->data = I ; P->pnext = q;//p in front of Q so p points to q p = q;//this time p is Q, because to create later, that is, Q becomes the precursor of the next node P->pnext = head;//The last node pointing to the head form a circular list return head; void Josephus (Node *head,int k,int m)//from the person numbered K (1<=k<=n) began to count, the number to m of the person to dequeue; {int i; Node *p = HEAD,*TMP1; while (p->data! = k)//p points to the node data is K, first finds the position of the starting number p = p->pnext; while (p->pnext! = p)//analog count off the process until the rest of one's own, when there is only one he points from{for (i=1;i<m;i++)//number to ' m ' {tmp1 = P;//TMP1 is used here to record the previous person of the outbound person p = p->pnext; } printf ("%d", p->data);//output out of the person's number//The essence of the list in the following section, look at my hair pictures, better than the array tmp1->pnext= p->p next;//just change the data element that the pointer points to, you can get rid of the person, from his next position to start the number of free (p);//release P point to the memory space, completely empty out the position of the person he does not exist P = tmp1->pnext; Next round start position} printf ("\nthe lucky people is%d\n", p->data);//FINAL winner free (p);//release P points to memory space} int main () {int N,m,s; scanf ("%d%d%d", &n,&m,&s); Node *head = Create (n);//Call function creates a cyclic list Josephus (head,s,m) with n nodes;//Call the function of the analog Josephus return 0;}
Loop linked list implementation Joseph Ring