栈:last in first out
1.MStackADT.h
#ifndef MSTACKADT_H
#define MSTACKADT_H
/*
Create by软件工程 gpwner 2016年11月20日
*/
template<class T>
class MStackADT
{
public:
MStackADT();
virtual ~MStackADT();
//栈的初始化
virtual void initializeStack() = 0;
//栈是否为空
virtual bool isEmptyStack() const = 0;
//栈是否已满
virtual bool isFullStack() const = 0;
//插入数据
virtual void push(const T& newItem) = 0;
//获取栈中的数据
virtual T top() const = 0;
//弹出数据
virtual void pop() = 0;
private:
};
#endif // MSTACKADT_H
2.MStack.h
#ifndef STACKTYPE_H
#define STACKTYPE_H
#include<MStackADT.h>
#include <iostream>
#include <cassert>
using namespace std;
template <class T>
class stackType: public MStackADT<T>
{
public:
const stackType<T>& operator=(const stackType<T>&);
void initializeStack()
{
stackTop = 0;
}
bool isEmptyStack() const
{
return(stackTop == 0);
}
bool isFullStack() const
{
return(stackTop == maxStackSize);
}
void push(const T& newItem)
{
if (!isFullStack())
{
arr[stackTop] = newItem; //add newItem to the
//top of the stack
stackTop++; //increment stackTop
}
else
cout << "Cannot add to a full stack." << endl;
}
T top() const
{
assert(stackTop != 0); //if stack is empty,
//terminate the program
return arr[stackTop - 1];
}
void pop()
{
if (!isEmptyStack())
stackTop--; //decrement stackTop
else
cout << "Cannot remove from an empty stack." << endl;
}
stackType(int stackSize = 100)
{
if (stackSize <= 0)
{
cout << "Size of the array to hold the stack must "
<< "be positive." << endl;
cout << "Creating an array of size 100." << endl;
maxStackSize = 100;
}
else
maxStackSize = stackSize;
stackTop = 0;
arr = new T[maxStackSize]; //create the array to
}
stackType(const stackType<T>& otherStack)
{
delete [] arr;
maxStackSize = otherStack.maxStackSize;
stackTop = otherStack.stackTop;
arr = new T[maxStackSize];
//copy otherStack into this stack
for (int j = 0; j < stackTop; j++)
arr[j] = otherStack.arr[j];
}
~stackType()
{
delete [] arr; //
}
private:
int maxStackSize;
int stackTop;
T *arr;
void copyStack(const stackType<T>& otherStack);
};
#endif // STACKTYPE_H
注意:在code blocks下,模板类的方法的实现是不能在.cpp文件中写的,必须在.h文件中写。否则会报错,说你的模板的类没有实现。
本文介绍了一个通用栈数据结构的C++实现,包括栈的基本操作如push、pop等,并通过一个具体的栈类stackType来演示如何使用该抽象数据类型。文章详细展示了栈的初始化、检查空满状态等功能。

被折叠的 条评论
为什么被折叠?



