The algorithm given in the book is a bit of a waste of space, you can use the loop queue to improve, so that you do not need to use additional space, the original array based on the decryption can be done, the code is as follows:
1#include <stdio.h>2 3 voidDecodeintA[],intsize)4 {5 intHead =0, tail = size;//tail point to next position to be written6 7 while(Head! =tail) {8 //Delete team first element9printf"%2d", A[head]);TenHead = (head +1) %size; One A //Add new team first elements to the end of the team -A[tail% size] =A[head]; -Tail = (tail +1)% size;//you can avoid situations in which the queue is full and the queue is empty with the same state the //and the team's first team . -Head = (head +1) %size; - } - } + - intMainvoid) + { A inta[ -], size =0, I; at - while(SCANF ("%d", &a[size])! =EOF) { -++size; - } - -printf"Size:%d\n", size); in - Decode (A, size); to + return 0; -}
In the code, head points to the top of the team, and tail points to the next position in the tail, in this way, if the delete operation Head==tail indicates that the queue is empty, head==tail indicates that the queue is full when the insert operation is performed. Supposedly, tail should be written as tail=0 at initialization, but this will cause the while condition to be out of order and therefore set the tail=size, but the cost is to say that the new team's first element is always labeled with the A[tail% size] when it is added to the end of the team. Of course, we can also use the do-while structure to solve this problem.
1 voidDecodeintA[],intsize)2 {3 intHead =0, tail =0;//tail point to next position to be written4 5 Do {6 //Delete team first element7printf"%2d", A[head]);8Head = (head +1) %size;9 Ten //Add new team first elements to the end of the team OneA[tail] =A[head]; ATail = (tail +1)% size;//you can avoid situations in which the queue is full and the queue is empty with the same state - //and the team's first team . -Head = (head +1) %size; the} while(Head! =tail); -}
Ah ha! Algorithm: Decrypt QQ number