1.复习两个知识点先:
-
define语句是不要分号结尾的(这个很容易记住,因为我们写#include语句的时候也没有加过分号的把!);
-
模板类的声明方法:注意我们在类体外定义类的函数的时候,一定要为每个函数加上template语句,并且使用域作用符::时要指定类型;
2.实现说明:
这里是用数组实现的栈,下一次使用链表实现之。
在使用数组实现栈的过程中,有个问题值得讨论,就是这个栈顶指针(top)到底应该指向栈顶的那个元素还是指向栈顶那个元素的下一个空位置呢?
这两种方法都是可行的。本代码使用的前一种,其带来了如下好处:
-
遍历输出栈时,计数器i从0变化到top就可以了,即for(int i = 0; i < top; i++)就可以了,这和处理边界问题时遵循的“前闭后开”是吻合的;
-
判定栈为空时,直接判定其是不是0即可,这和我们的语言习惯是吻合的;
我目前发现的这么做的最好的有点就是以上两点了。
3.代码:
#include <iostream>
using namespace std;
#define EMPTY 0
template <class type>
class stack{
public:
stack(const int stackSize);
stack(const stack<type> &otherStack);
~stack();
void destroyStack();
void copy(const stack<type> &otherStack);
bool isEmpty();
bool isFull();
void push(const type x);
type top();
type pop();
void print();
public:
int maxSize;
int stackTop;
int *array;
};
template <class type>
stack<type>::stack(const int stackSize)
{
if(0 > stackSize)maxSize = 100;
else maxSize = stackSize;
stackTop = 0;
array = new type[maxSize];
for(int i = 0; i< maxSize; i++)
array[i] = 0;
}
template <class type>
stack<type>::stack(const stack<type> &otherStack)
{
if(NULL == otherStack)return;
copy(otherStack);
}
template <class type>
void stack<type>::copy(const stack<type> &otherStack)
{
maxSize = otherStack.maxSize;
array = new type[maxSize];
stackTop = otherStack.stackTop;
for (int i = 0; i < stackTop; i++)
array[i] = otherStack.array[i];
}
template <class type>
void stack<type>::print()
{
for(int i = 0; i < stackTop; i++)
cout << array[i] << endl;
cout << "print stack over" << endl;
}
template <class type>
bool stack<type>::isEmpty()
{
if(EMPTY == stackTop) return true;
else return false;
}
template <class type>
bool stack<type>::isFull()
{
if(stackTop == maxSize)return true;
else return false;
}
template <class type>
void stack<type>::push(const type x)
{
if( true == isFull() )return;
array[stackTop++] = x;
}
template <class type>
type stack<type>::top()
{
if(true == isEmpty() )return -1;
return array[stackTop-1];
}
template <class type>
type stack<type>::pop()
{
if(true == isEmpty() )return -1;
return array[--stackTop];
}
template <class type>
stack<type>::~stack()
{
delete [] array;
}
int main()
{
stack<int> s(10);
for(int i = 0; i<11; i++)
s.push(i);
s.print();
s.pop();
s.print();
return 0;
}
4.总结:
写栈的代码时,要注意进栈和出栈时要判定栈是否空或者是否满,这是必须要考虑到的,否则必然出错。