

新闻资讯
常见问题栈的实现方式分为3种

栈的函数需要实现如下所示:
T pop() : 出栈并返回栈顶元素void push(const T &t) : 入栈 const T & top() const : 获取const类型栈顶元素T &top() : 获取栈顶元素int length() const: 获取数量(父类已经实现)void clear(): 清空栈(父类已经实现)本章,我们实现的栈基于动态数组实现,它的父类是我们之前实现的Vector类:
C++ 动态数组模版类Vector实例详解
所以代码实现会非常简单.
代码如下所示:
#ifndef Stack_H
#define Stack_H
#include "throw.h"
// throw.h里面定义了一个ThrowException抛异常的宏,如下所示:
//#include <iostream>
//using namespace std;
//#define ThrowException(errMsg) {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);}
#include "Vector.h"
template<class T>
class Stack : public Vector<T>
{
public:
T pop()
{
if(Vector<T>::isEmpty()) { // 如果栈为空,则抛异常
ThrowException("Stack is empty ...");
}
T t = Vector<T>::data()[Vector<T>::length() - 1];
Vector<T>::resize(Vector<T>::length() - 1);
return t;
}
// 入栈,实际就是append尾部添加成员
void push(const T &t)
{
Vector<T>::append(t);
}
T &top()
{
if(Vector<T>::isEmpty()) {
ThrowException("Stack is empty ...");
}
return Vector<T>::data()[Vector<T>::length() - 1];
}
const T &top() const
{
if(Vector<T>::isEmpty()) {
ThrowException("Stack is empty ...");
}
return Vector<T>::data()[Vector<T>::length() - 1];
}
};
#endif // Stack_H
int main(int argc, char *argv[])
{
Stack<int> stack;
cout<<"******* current length:"<<stack.length()<<endl;
for(int i = 0; i < 5; i++) {
cout<<"stack.push:"<<i<<endl;
stack.push(i);
}
cout<<"******* current length:"<<stack.length()<<endl;
while(!stack.isEmpty()) {
cout<<"stack.pop:"<<stack.pop()<<endl;
}
return 0;
}
运行打印:
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!