There is a one-way cyclic linked list, reporting data from the beginning, reporting elements that are multiples of M or M. A one-way cyclic linked list is formed based on the order of departure.
Function prototype: void reorder (node ** head, int m );
I personally think that this question is a variant of Joseph's ring.
The method is to report the number in sequence along the cyclic linked list. If the report number can be divisible by m, the node will be deleted from the original linked list and linked to the new linked list.
The condition for loop termination is that only the last node is left, that is, p-> next = P
# Include "stdafx. H "# include <iostream> # include <algorithm> # include <windows. h> using namespace STD; typedef struct node {int data; struct node * Next;} node, * List; List createlistwithouthead (int n) // create a circular linked list with no leading nodes {If (n = 0) return NULL; List head = (list) malloc (sizeof (node )); head-> DATA = 1; head-> next = NULL; list p = head; List q = NULL; For (INT I = 2; I <= N; I ++) {q = (list) malloc (sizeof (node); q-> DATA = I; q-> next = NULL; P-> next = Q; P = Q;} p-> next = head; // The Last Pointer Points to the first node return head;}/* head is the original linked list, n is the length of the linked list. If n is a node multiple of M, It is deleted from the original linked list and added to the new cyclic queue */void reorder (node ** head, int m) {node * P, * Pre, * tail; // pre and P are used to traverse the original linked list, while tail is the end pointer of the new linked list pre = P = * head; node * newhead = (node *) malloc (sizeof (node); newhead-> next = NULL; tail = newhead; int COUNT = 1; while (p-> next! = P) // condition for cyclic termination: Only one node is left, pointing to itself {count ++; Pre = P; P = p-> next; if (count % m = 0) {// cout <p-> data <""; // sleep (1000 ); pre-> next = p-> next; // Delete the P node from the original linked list. Tail-> next = P; // send the P node to the tail of the new linked list; // now p becomes the End Node of the new linked list. Tail-> next = newhead-> next; // The end pointer is directed back to the header to form the loop structure P = pre-> next; // P points to the next node that can be traversed, Count ++; // count + 1 }}// process the only remaining element // cout <p-> data <"; tail-> next = P; tail = P; tail-> next = newhead-> next; * head = newhead-> next;} void Traver Sewithouthead (list head) // traverse the circular linked list with no leading node {If (Head = NULL) return; list p = head; do {cout <p-> data <"; P = p-> next;} while (P! = Head); cout <Endl;} int main () {int n = 20, M = 3; // a circular linked list with a length of 20, nodes in multiples of 3 are listed and added to the new linked list. List head = createlistwithouthead (n); traversewithouthead (head); reorder (& head, 3); traversewithouthead (head ); getchar (); Return 0 ;}