【练习3.21】

编写仅用一个数组而实现两个栈的例程。除非数组的每一个单元都被使用,否则栈例程不能有溢出声明。

 

Answer:

很简单,一个栈从数组头起,一个栈从数组尾起,分别保留左右栈头索引。

如left=5则表示array[0]~array[4]为左栈元素,right=7则表示array[8]~array[size-1]为右栈元素。

当左右索引交叉时(left=right+1),0~left-1为左栈,left~size-1为右栈,刚好用完每一个单元。

测试代码:

 1 #include <iostream>
 2 #include "stack.h"
 3 using namespace std;
 4 using namespace stack;
 5 template class Stack<int>;
 6 int main(void)
 7 {
 8     Simu_Double_Stack<int> test(12);
 9     //测试插入
10     test.leftpush(2);
11     test.leftpush(3);
12     test.leftpush(5);
13     test.leftpush(7);
14     test.leftpush(13);
15     test.rightpush(97);
16     test.rightpush(89);
17     test.rightpush(83);
18     test.rightpush(79);
19     test.rightpush(73);
20     test.rightpush(71);
21     //测试打印
22     test.leftprint();
23     test.rightprint();
24     cout << endl;
25     //测试拷贝
26     Simu_Double_Stack<int> test2;
27     test2 = test;
28     test2.leftprint();
29     test2.rightprint();
30     cout << endl;
31     //证明拷贝为深拷贝
32     test.leftpush(11);
33     test2.leftprint();
34     cout << endl;
35     test.leftprint();
36     cout << endl;
37     //测试栈满报错
38     test.leftpush(10);
39     test.rightpush(82);
40     //测试出栈
41     test.leftpop();
42     test.leftpop();
43     test.rightpop();
44     test.rightpop();
45     test.leftprint();
46     test.rightprint();
47     //测试栈元素清空
48     test.leftclear();
49     test.rightclear();
50     test.leftprint();
51     test.rightprint();
52 
53 
54     system("pause");
55 }
View Code

相关文章: