C + + implementation of stack and queue

In linear table, the first in first out is called queue, and the first in last out is called stack. Queues are often used in BFS. When the recursion level of the function is too high, the recursive process needs to be implemented manually, and a "manual stack" needs to be written.

Sometimes, we will have a lot of data in and out of the queue frequently, but there are not many elements in it at the same time, so we need to write "circular queue". The code is not difficult, but the statements with increasing subscripts are worth considering.

k=(k+1)%maxn;

This sentence uses the modular operation%, which is a waste of time. If% can be avoided, the running speed of code can be greatly improved. I did a test. I ran the following five sentence writing methods for 5 × 10 ^ 8 times respectively, and ran 5 times on my machine with CodeBlocks 10.05, and took the average. The time is as follows:

i=(i==maxn-1)?0:(i+1);          // 582 s
if(i==maxn-1) i=0; else ++i;    // 588s
++i; if(i==maxn) i=0;           // 605s
++i; i=(i==maxn)?0:i;           // It took 2.040s
i=(i+1)%maxn;                   // 538 s

Considering the error of codeblocks itself, I only remove this statement and average the rest of the code under codeblocks for 5 times. The time is 0.015s.

Therefore, the first two statements are the fastest, the third is good, the fourth is slower, and the last one takes three times the time. Therefore, my code uses the first line of writing, I suggest you try to use the first three lines of writing.

The code is given below:

 // Suppose the information type stored is int
 
 // Stack
 class Stack
 {
     static const int maxn = 10000;
     int S[maxn],L;
 public:
     Stack(): L(0) {}
     void in(int x) { S[L++]=x; }
     int out() { return S[--L]; }
     int size() { return L; }
 };
 
 // queue
 class Queue
 {
     static const int maxn = 10000;
     int Q[maxn],i,j;
 public:
     Queue(): i(0), j(0) {}
     void in(int x) { Q[j++]=x; }
     int out() { return Q[i++]; }
     int size() { return j-i; }
 };
 
 // Circular queue
 class CycleQueue
 {
     static const int maxn = 10000;
     int Q[maxn],i,j;
     void add(int &k) { k=(k==maxn-1)?0:(k+1); }
 public:
     CycleQueue(): i(0), j(0) {}
     void in(int x) { Q[j]=x; add(j); }
     int out() { int x=Q[i]; add(i); return x; }
     int size() { return (j>i)?(j-i):(j+maxn-i); } // Here we remind that the number of circular queue elements should be between 0~maxn-1, not maxn
38 };

 

Tags: REST

Posted on Tue, 30 Jun 2020 03:28:29 -0400 by appels