《数据结构》C++代码 栈与队列

         线性表中,先进先出的叫队列,先进后出的叫栈。队列常用于BFS,而在函数递归层数过高时,需要手动实现递归过程,这时候便需要写一个“手动栈”。

         有时候,我们会有大量数据频繁出入队列,但同时存在其内的元素却不多,此时需要写“循环队列”。其代码并不难,但里面下标递增的语句值得斟酌一下。

k=(k+1)%maxn;

         这句话用到了取模运算%,是非常浪费时间的。若能避免使用%,则可以大大提高代码运行速度。我做了一个测试,把下面五种语句写法分别运行5×10^8次,在我的机器上用codeblocks10.05各运行5次,取平均数,时间如下所示:

1 i=(i==maxn-1)?0:(i+1);          // 用时1.582s
2 if(i==maxn-1) i=0; else ++i;    // 用时1.588s
3 ++i; if(i==maxn) i=0;           // 用时1.605s
4 ++i; i=(i==maxn)?0:i;           // 用时2.040s
5 i=(i+1)%maxn;                   // 用时4.538s

考虑到codeblocks本身的误差,我单单除去这条语句,将代码其余部分在codeblocks下的运行,依旧5次取平均,时间为:0.015s

  因此,算入误差可以发现,前两条语句最快,第三条也不错,第四条较慢,最后一条用了3倍的时间。故而我的代码中采用了第一行的写法,建议大家尽量采用前三行的写法。

下面给出代码:

 1 // 假设储存的信息类型是int
 2 
 3 //
 4 class Stack
 5 {
 6     static const int maxn = 10000;
 7     int S[maxn],L;
 8 public:
 9     Stack(): L(0) {}
10     void in(int x) { S[L++]=x; }
11     int out() { return S[--L]; }
12     int size() { return L; }
13 };
14 
15 // 队列
16 class Queue
17 {
18     static const int maxn = 10000;
19     int Q[maxn],i,j;
20 public:
21     Queue(): i(0), j(0) {}
22     void in(int x) { Q[j++]=x; }
23     int out() { return Q[i++]; }
24     int size() { return j-i; }
25 };
26 
27 // 循环队列
28 class CycleQueue
29 {
30     static const int maxn = 10000;
31     int Q[maxn],i,j;
32     void add(int &k) { k=(k==maxn-1)?0:(k+1); }
33 public:
34     CycleQueue(): i(0), j(0) {}
35     void in(int x) { Q[j]=x; add(j); }
36     int out() { int x=Q[i]; add(i); return x; }
37     int size() { return (j>i)?(j-i):(j+maxn-i); } // 此处提醒,循环队列元素个数应在0~maxn-1之间,不可达到maxn
38 };

 

posted on 2014-12-04 11:40  IceDream61  阅读(968)  评论(0编辑  收藏  举报

导航